PHP addcslashes() Function

Quick summary: The PHP addcslashes() function returns a string with backslashes before the characters that are listed in the characters parameter.

PHP addcslashes() Syntax

addcslashes(string $string, string $characters): string
PHP

PHP addcslashes() Basic examples

echo addcslashes("Hello World", "A..Z");
PHP
Output:
\H\ello \W\orld

Escapes uppercase letters using a character range.

echo addcslashes("foo[ ]", "[]");
PHP
Output:
foo\[ \]

Escapes specific characters.

PHP addcslashes() Real-world usage

$input = "Line1\nLine2";
echo addcslashes($input, "\n");
PHP
Output:
Line1\\nLine2

Escapes newline characters for safe output.

PHP addcslashes() Edge cases

echo addcslashes("test", "");
PHP
Output:
test

If no characters are specified, string remains unchanged.

PHP addcslashes() Common mistakes

Confusing addcslashes() with addslashes()

addcslashes() escapes based on a character list or range.

Incorrect
addcslashes("O'Reilly", "'");
Correct
addslashes("O'Reilly");

Use addslashes() for simple quote escaping.

PHP addcslashes() Frequently Asked Questions

What does addcslashes() do?

Escapes characters with backslashes.

Use case?

Preparing strings for output.

Difference from addslashes()?

Allows custom character list.

Common mistake?

Wrong char range.

Does it modify string?

Returns new string.

Handles binary?

Yes.

Performance?

Fast.

Safe?

Depends on use.

Alternative?

preg_replace().

Supports ranges?

Yes.

Used in escaping?

Yes.

Best practice?

Use carefully.

PHP addcslashes() Related PHP Functions