addcslashes
addcslashes(string $string, string $characters): string
Escapes a string C-style for the given character list (\n\t\0 become C escape sequences; ranges use the ".." syntax) — pairing with addslashes's "quote-like characters only" strategy.
C C23
#include <stdio.h>
#include <string.h>
/* PHP addcslashes in miniature: escape control chars and a given set */
static void c_escape(const char *s, const char *chars, char *out) {
size_t k = 0;
for (; *s; s++) {
unsigned char ch = (unsigned char)*s;
if (ch == '\n') { out[k++] = '\\'; out[k++] = 'n'; }
else if (ch == '\t') { out[k++] = '\\'; out[k++] = 't'; }
else if (strchr(chars, ch) != NULL) { out[k++] = '\\'; out[k++] = (char)ch; }
else { out[k++] = (char)ch; }
}
out[k] = '\0';
}
int main(void) {
char buf[64] = {0};
c_escape("A\tB\nC", "", buf);
printf("%s\n", buf);
c_escape("abcdef", "abc", buf);
printf("%s\n", buf);
return 0;
}
A\tB\nC \a\b\cdef
C++ C++26
#include <iostream>
#include <string>
// PHP addcslashes in miniature: escape control chars and a given set
static std::string c_escape(const std::string &s, const std::string &chars) {
std::string out;
for (unsigned char ch : s) {
if (ch == '\n') { out += "\\n"; }
else if (ch == '\t') { out += "\\t"; }
else if (chars.find(static_cast<char>(ch)) != std::string::npos) { out += '\\'; out += static_cast<char>(ch); }
else { out += static_cast<char>(ch); }
}
return out;
}
int main() {
std::cout << c_escape("A\tB\nC", "") << "\n";
std::cout << c_escape("abcdef", "abc") << "\n";
return 0;
}
A\tB\nC \a\b\cdef
C# v11.0.100
// PHP addcslashes in miniature: escape control chars and a given set
static string CEscape(string s, string chars) {
var b = new System.Text.StringBuilder();
foreach (char ch in s) {
if (ch == '\n') b.Append("\\n");
else if (ch == '\t') b.Append("\\t");
else if (chars.IndexOf(ch) >= 0) { b.Append('\\'); b.Append(ch); }
else b.Append(ch);
}
return b.ToString();
}
Console.WriteLine(CEscape("A\tB\nC", ""));
Console.WriteLine(CEscape("abcdef", "abc"));
A\tB\nC \a\b\cdef
Go v1.27.4
package main
import (
"fmt"
"strings"
)
// PHP addcslashes in miniature: escape control chars and a given set
func cEscape(s, chars string) string {
out := ""
for i := 0; i < len(s); i++ {
ch := s[i]
switch {
case ch == '\n':
out += "\\n"
case ch == '\t':
out += "\\t"
case strings.ContainsRune(chars, rune(ch)):
out += "\\" + string(ch)
default:
out += string(ch)
}
}
return out
}
func main() {
fmt.Println(cEscape("A\tB\nC", ""))
fmt.Println(cEscape("abcdef", "abc"))
}
A\tB\nC \a\b\cdef
Java v27.0.1
public class Main {
// PHP addcslashes in miniature: escape control chars and a given set
static String cEscape(String s, String chars) {
StringBuilder b = new StringBuilder();
for (char ch : s.toCharArray()) {
if (ch == '\n') b.append("\\n");
else if (ch == '\t') b.append("\\t");
else if (chars.indexOf(ch) >= 0) { b.append('\\'); b.append(ch); }
else b.append(ch);
}
return b.toString();
}
public static void main(String[] args) {
System.out.println(cEscape("A\tB\nC", ""));
System.out.println(cEscape("abcdef", "abc"));
}
}
A\tB\nC \a\b\cdef
JavaScript v26.13.1
// PHP addcslashes in miniature: escape control chars and a given set
function cEscape(s, chars) {
let out = "";
for (const ch of s) {
if (ch === "\n") out += "\\n";
else if (ch === "\t") out += "\\t";
else if (chars.includes(ch)) out += "\\" + ch;
else out += ch;
}
return out;
}
console.log(cEscape("A\tB\nC", ""));
console.log(cEscape("abcdef", "abc"));
A\tB\nC \a\b\cdef
PHP v8.6.0
// C-style escaping: control chars become \n, \t, \0 sequences
$range = "\0..\37";
echo addcslashes("A\tB\nC", $range), "\n";
// ranges use the ".." syntax (not "-"): a..c escapes a, b and c
echo addcslashes("abcdef", "a..c"), "\n";
// contrast: addslashes only escapes quote-like characters
echo addslashes("a'b\"c\\d"), "\n";
// NUL must be listed explicitly, or it truncates the string
echo addcslashes("any\0body", "\0"), "\n";
A\tB\nC \a\b\cdef a\'b\"c\\d any\000body
Python v3.15.2
# PHP addcslashes in miniature: escape control chars and a given set
def c_escape(s: str, chars: str) -> str:
out = []
for ch in s:
if ch == "\n":
out.append("\\n")
elif ch == "\t":
out.append("\\t")
elif ch in chars:
out.append("\\" + ch)
else:
out.append(ch)
return "".join(out)
print(c_escape("A\tB\nC", ""))
print(c_escape("abcdef", "abc"))
A\tB\nC \a\b\cdef
Rust v1.99.1
// PHP addcslashes in miniature: escape control chars and a given set
fn c_escape(s: &str, chars: &str) -> String {
let mut out = String::new();
for ch in s.chars() {
match ch {
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
_ if chars.contains(ch) => {
out.push('\\');
out.push(ch);
}
_ => out.push(ch),
}
}
out
}
fn main() {
println!("{}", c_escape("A\tB\nC", ""));
println!("{}", c_escape("abcdef", "abc"));
}
A\tB\nC \a\b\cdef
TypeScript v26.13.1
// PHP addcslashes in miniature: escape control chars and a given set
function cEscape(s: string, chars: string): string {
let out = "";
for (const ch of s) {
if (ch === "\n") out += "\\n";
else if (ch === "\t") out += "\\t";
else if (chars.includes(ch)) out += "\\" + ch;
else out += ch;
}
return out;
}
console.log(cEscape("A\tB\nC", ""));
console.log(cEscape("abcdef", "abc"));
A\tB\nC \a\b\cdef
Language differences
C: the origin of addcslashes — a hand-written per-character escape shows the C-style escaping shape (example); C strings terminate at NUL, which is exactly the semantics addcslashes mirrors for NUL.
C++: std::string with a range-for for the same escape (example); the '\n'/'\t' C escape semantics match what PHP produces.
C#: hand-written StringBuilder escaping (example); Regex.Replace would also work, but the loop is closer to addcslashes's per-character set lookup.
Go: strings.ContainsRune for the set plus a hand-written loop (example); Go strings are byte sequences like PHP, so iteration is by byte.
Java: hand-written char loop (example); String.translateEscapes (15+) is the reverse direction (escape sequences to real characters).
JavaScript: hand-written loop (example); JSON.stringify escapes control characters but with JSON semantics (\u001f and the like), not C escapes.
PHP: the range syntax in the characters argument is ".." ("a..z"); writing "a-z" escapes only a, - and z — a classic trap; "\0..\37" covers every ASCII control character; without NUL in the list the string truncates (not binary safe) — "any\000body" in the example is the result of listing it explicitly; versus addslashes: addslashes handles only quote-like characters (legacy database escaping), while addcslashes is the general C-style escape.
Python: hand-written loop (example); the standard library has no direct counterpart — codecs.encode(s, 'unicode_escape') escapes all non-ASCII but with different semantics (\xe4 shapes).
Rust: hand-written match loop (example); the built-in escape_debug/escape_default are the same family (C-style escapes).
TypeScript: same hand-written loop as JavaScript (example); no impact at the type layer.