PHP addcslashes() Function

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The addcslashes() function adds backslashes before specific characters you choose. It is ideal when you need fine-grained control over which symbols get escaped—for example, only single quotes in a message, or every lowercase letter in a custom filter.

01

Selective Escape

Pick exact characters via charlist.

02

Character Ranges

Use a-z and octal ranges.

03

Two Parameters

String plus charlist to escape.

04

Returns String

Original string stays unchanged.

05

Regex Prep

Escape metacharacters safely.

06

vs addslashes()

Know when to use each function.

Definition and Usage

In PHP, addcslashes() is a built-in string function that returns a copy of the input string with a backslash inserted before every character that appears in the $charlist argument. For example, escaping single quotes in "Hello, 'World'!" produces Hello, \'World\'!.

💡
Beginner Tip

addcslashes() is for selective escaping. If you just need standard quote escaping (like before storing data), look at addslashes() next. For HTML output, use htmlspecialchars(). For databases, always prefer prepared statements.

📝 Syntax

The addcslashes() function accepts two string parameters:

PHP
string addcslashes(string $str, string $charlist)

Parameters

  • $str — the input string to process.
  • $charlist — characters to escape. Can include individual characters, hyphen ranges (e.g. a-z), or octal ranges (e.g. \0..\37 for ASCII control characters).

Return Value

Returns a new string with backslashes added before the specified characters. The original $str is not modified.

⚡ Quick Reference

InputcharlistResult
"Hello, 'World'!""'"Hello, \'World\'!
"C:\temp\file.txt""\\"C:\\temp\\file.txt
"abc123""a-c"\a\b\c123
"test""a-z"\t\e\s\t
"""'""" (empty)
Basic
addcslashes($s, "'")

Escape single quotes

Range
addcslashes($s, "a-z")

Escape lowercase letters

Reverse
stripcslashes($escaped, "'")

Remove added slashes

Compare
addslashes($s)

Escapes ', ", \, NUL

Examples Gallery

Run these examples in any PHP 7+ environment. Each one demonstrates a common pattern beginners encounter with addcslashes().

📚 Getting Started

Start with the classic example: escaping single quotes inside a string.

Example 1 — Escape Single Quotes

The most common beginner use case: add backslashes before apostrophes so the string is safe inside single-quoted PHP code or similar contexts.

PHP
<?php
$original = "Hello, 'World'!";
$escaped  = addcslashes($original, "'");

echo "Original: $original\n";
echo "Escaped:  $escaped\n";
?>

How It Works

  • $original stays unchanged; addcslashes() returns a new string.
  • The charlist is a single character: ' (single quote).
  • Every apostrophe in the string gets a backslash prefix: \'.

Example 2 — Escape Multiple Characters

List several characters in charlist to escape them all at once.

PHP
<?php
$path = 'C:\Users\name\Documents';
$safe = addcslashes($path, "\\'");

echo $safe . "\n";
?>

How It Works

The charlist "\\'" tells PHP to escape backslashes and single quotes. This is useful when building strings that will be embedded in single-quoted literals.

📈 Practical Patterns

Ranges and comparisons you will see in real PHP code.

Example 3 — Character Range (a–z)

Use a hyphen range in charlist to escape every lowercase letter.

PHP
<?php
$text = "PHP 8 is fun!";
$result = addcslashes($text, "a-z");

echo $result . "\n";
?>

How It Works

  • a-z in charlist matches every lowercase letter from a through z.
  • Uppercase letters, digits, and spaces are left untouched.
  • Octal ranges like \0..\37 work the same way for control characters.

Example 4 — Preparing Text for Regular Expressions

When building a regex pattern dynamically, escape special regex characters so they are treated as literals.

PHP
<?php
$userInput = "price.is $9.99 (USD)";
$escaped   = addcslashes($userInput, ".$()*\\");

$pattern = "/^" . $escaped . "$/";
echo "Pattern: $pattern\n";
echo preg_match($pattern, $userInput) ? "Match!\n" : "No match\n";
?>

How It Works

For regex work, PHP provides preg_quote() which is usually the better choice. This example shows how addcslashes() lets you escape only the characters you list—useful when you understand exactly which metacharacters appear in your pattern.

Example 5 — addcslashes() vs addslashes()

See the difference side by side on the same input string.

PHP
<?php
$text = 'She said "Hi" and it\'s fine\\';

echo "addcslashes (quotes only):\n";
echo addcslashes($text, "'\"") . "\n\n";

echo "addslashes (default set):\n";
echo addslashes($text) . "\n";
?>

How It Works

addcslashes() only escapes characters you list in charlist. addslashes() always escapes single quotes, double quotes, backslashes, and the NUL byte—regardless of charlist. Pick the function that matches your escaping needs.

🚀 Common Use Cases

  • Custom string filters — escape only the characters your parser treats as special.
  • Building dynamic regex — prefix backslashes before metacharacters (though preg_quote() is preferred).
  • Legacy code maintenance — read older PHP that uses charlist-based escaping.
  • Data serialization — prepare strings for formats that require selective escaping.
  • Learning string handling — understand how PHP inserts escape characters before moving to higher-level tools like prepared statements.

🧠 How addcslashes() Works

1

PHP reads both arguments

You pass the source string and a charlist describing which characters need escaping.

Input
2

Characters are matched

PHP scans each character in $str. If it appears in charlist (or falls inside a defined range), a backslash is inserted before it.

Transform
3

A new string is returned

The original string is unchanged. Store the result in a variable or pass it to another function.

Output
=

Safely escaped text

Ready for embedding, parsing, or further processing in your chosen context.

📝 Notes

  • Hyphen ranges in charlist expand to every character in the range—be careful with unintended matches (e.g. a-z includes every lowercase letter).
  • If charlist starts with .., the next two characters define an inclusive range (PHP-specific syntax).
  • Use stripcslashes() to reverse escaping with the same charlist.
  • Do not rely on addcslashes() for SQL safety—use prepared statements instead.
  • For HTML output, prefer htmlspecialchars() or htmlentities().

Conclusion

The addcslashes() function gives you precise control over character escaping in PHP. By choosing exactly what goes into charlist, you can prepare strings for custom parsers, regex patterns, or legacy integrations without over-escaping unrelated characters.

Remember: selective escaping with addcslashes(), standard quote escaping with addslashes(), HTML safety with htmlspecialchars(), and database safety with prepared statements. Each tool has its place.

💡 Best Practices

✅ Do

  • Define charlist as narrowly as possible for your use case
  • Use preg_quote() when escaping for regular expressions
  • Pair with stripcslashes() when you need to undo escaping
  • Test edge cases like empty strings and backslash-heavy input
  • Prefer prepared statements for all database interactions

❌ Don’t

  • Use addcslashes() as your primary SQL injection defense
  • Assume addcslashes() and addslashes() are interchangeable
  • Use overly broad ranges like a-zA-Z0-9 unless you truly need them
  • Forget that the original string is never modified in place
  • Output raw escaped strings to HTML without proper encoding

Key Takeaways

Knowledge Unlocked

Five things to remember about addcslashes()

Use these points whenever you escape characters in PHP strings.

5
Core concepts
🔄 02

Returns New String

Original stays the same.

Behavior
🛠 03

Range Support

a-z and octal ranges.

Syntax
🔒 04

Not for SQL

Use prepared statements.

Security
05

stripcslashes()

Reverses the escaping.

Companion

❓ Frequently Asked Questions

addcslashes() returns a new string with a backslash inserted before every character listed in the charlist argument. You choose exactly which characters to escape, unlike addslashes() which always escapes quotes, backslashes, and the NUL byte.
string addcslashes(string $str, string $charlist). The first parameter is the input string; the second is a list of characters (or ranges) to escape with a backslash.
You can use hyphen ranges such as a-z or A-Z inside charlist. PHP also supports octal ranges like \0..\37 for control characters. If charlist begins with .., PHP treats the next two characters as an inclusive range.
addslashes() automatically escapes single quotes, double quotes, backslashes, and NUL. addcslashes() lets you pick any characters via charlist. Use addcslashes() when you need selective escaping—for example, only single quotes or only letters a–z.
No. For database queries, use prepared statements (PDO or MySQLi). addcslashes() is for general string escaping in contexts like regular expressions or custom parsers—not as a substitute for proper SQL escaping.
Use stripcslashes(), the companion function that removes backslashes before characters listed in a charlist. It reverses the escaping performed by addcslashes().

Explore More PHP String Functions

Continue with addslashes(), htmlspecialchars(), and the rest of the string function reference.

Next: addslashes() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful