addslashes / stripslashes

addslashes(string $string): string — stripslashes(string $string): string

Escapes single quotes, double quotes, backslashes and NUL with backslashes, plus its inverse. A magic-quotes-era legacy: the manual explicitly warns it does NOT prevent SQL injection - prepared statements are the correct approach.

C C23

C23
#include <stdio.h>
#include <string.h>

/* hand-written addslashes: prefix ' " and \ with a backslash */
static void addslashes(const char *src, char *dst) {
    size_t n = 0;
    while (*src) {
        if (*src == '\'' || *src == '"' || *src == '\\') {
            dst[n++] = '\\';
        }
        dst[n++] = *src++;
    }
    dst[n] = '\0';
}

/* hand-written stripslashes: \" \' \\ collapse back to one char */
static void stripslashes(const char *src, char *dst) {
    size_t n = 0;
    while (*src) {
        if (*src == '\\' && src[1] != '\0'
            && (src[1] == '\'' || src[1] == '"' || src[1] == '\\')) {
            src++; // drop the backslash, keep the escaped char
        }
        dst[n++] = *src++;
    }
    dst[n] = '\0';
}

int main(void) {
    const char *s = "He said \"It's a \\ path"; // no NUL here: C strings end at '\0'
    char esc[64], back[64];
    addslashes(s, esc);
    puts(esc); // He said \"It\'s a \\ path
    stripslashes(esc, back);
    printf("%s\n", strcmp(back, s) == 0 ? "roundtrip ok" : "roundtrip failed");
    return 0;
}
Output
He said \"It\'s a \\ path
roundtrip ok

C++ C++26

C++26
#include <iostream>
#include <string>

// hand-written addslashes on std::string
static std::string addslashes(const std::string &s) {
    std::string out;
    for (char c : s) {
        if (c == '\'' || c == '"' || c == '\\') out += '\\';
        out += c;
    }
    return out;
}

// hand-written stripslashes
static std::string stripslashes(const std::string &s) {
    std::string out;
    for (size_t i = 0; i < s.size(); ++i) {
        if (s[i] == '\\' && i + 1 < s.size()
            && (s[i + 1] == '\'' || s[i + 1] == '"' || s[i + 1] == '\\')) {
            continue; // drop the backslash; the escaped char is copied next round
        }
        out += s[i];
    }
    return out;
}

int main() {
    std::string s = "He said \"It's a \\ path";
    std::string esc = addslashes(s);
    std::cout << esc << "\n"; // He said \"It\'s a \\ path
    std::cout << (stripslashes(esc) == s ? "roundtrip ok" : "roundtrip failed") << "\n";
    return 0;
}
Output
He said \"It\'s a \\ path
roundtrip ok

C# v11.0.100

v11.0.100
// no built-in addslashes — escape by hand; for SQL use parameterized queries instead
string s = "He said \"It's a \\ path";
var parts = s.Select(c => (c == '\'' || c == '"' || c == '\\') ? "\\" + c : c.ToString());
string esc = string.Concat(parts);
Console.WriteLine(esc); // He said \"It\'s a \\ path
string back = esc.Replace("\\'", "'").Replace("\\\"", "\"").Replace("\\\\", "\\");
Console.WriteLine(back == s ? "roundtrip ok" : "roundtrip failed");
Output
He said \"It\'s a \\ path
roundtrip ok

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

// hand-written addslashes; for SQL use parameterized queries (placeholders)
func addslashes(s string) string {
	var b strings.Builder
	for _, c := range s {
		switch c {
		case '\'', '"', '\\':
			b.WriteByte('\\')
		}
		b.WriteRune(c)
	}
	return b.String()
}

func main() {
	s := "He said \"It's a \\ path"
	esc := addslashes(s)
	fmt.Println(esc) // He said \"It\'s a \\ path
	back := strings.ReplaceAll(
		strings.ReplaceAll(
			strings.ReplaceAll(esc, "\\'", "'"),
			"\\\"", "\""),
		"\\\\", "\\")
	fmt.Println(back == s) // true
}
Output
He said \"It\'s a \\ path
true

Java v27.0.1

v27.0.1
public class Main {
    // hand-written addslashes; for SQL use PreparedStatement with ? placeholders instead
    static String addslashes(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == '\'' || c == '"' || c == '\\') sb.append('\\');
            sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String s = "He said \"It's a \\ path";
        String esc = addslashes(s);
        System.out.println(esc); // He said \"It\'s a \\ path
        String back = esc.replace("\\'", "'").replace("\\\"", "\"").replace("\\\\", "\\");
        System.out.println(back.equals(s)); // true
    }
}
Output
He said \"It\'s a \\ path
true

JavaScript v26.13.1

v26.13.1
// no built-in addslashes — escape by hand; for SQL use parameterized queries
const s = "He said \"It's a \\ path"
const esc = s.replace(/(['"\\])/g, '\\$1')
console.log(esc) // He said \"It\'s a \\ path
console.log(esc.replace(/\\(['"\\])/g, '$1') === s) // true
Output
He said \"It\'s a \\ path
true

PHP v8.6.0

v8.6.0
$s = "He said \"It's a \\ path\0end"; // contains " ' \ and a NUL byte
$esc = addslashes($s);
echo $esc, "\n";                     // " ' \ get a backslash each; NUL becomes \0
var_dump(stripslashes($esc) === $s); // round trip restores the original byte for byte
Output
He said \"It\'s a \\ path\0end
bool(true)

Python v3.15.2

v3.15.2
# no built-in addslashes — escape by hand; for SQL use parameterized queries (DB-API placeholders)
s = 'He said "It\'s a \\ path'
esc = ''.join(('\\' + c) if c in '\'"\\' else c for c in s)
print(esc)  # He said \"It\'s a \\ path
print(esc.replace("\\'", "'").replace('\\"', '"').replace('\\\\', '\\') == s)  # True
Output
He said \"It\'s a \\ path
True

Rust v1.99.1

v1.99.1
// no built-in addslashes — escape by hand; for SQL use bound query parameters
fn addslashes(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        if matches!(c, '\'' | '"' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

fn main() {
    let s = "He said \"It's a \\ path";
    let esc = addslashes(s);
    println!("{}", esc); // He said \"It\'s a \\ path
    let back = esc.replace("\\'", "'").replace("\\\"", "\"").replace("\\\\", "\\");
    println!("{}", back == s); // true
}
Output
He said \"It\'s a \\ path
true

TypeScript v26.13.1

v26.13.1
// no built-in addslashes — escape by hand; for SQL use parameterized queries
const s: string = "He said \"It's a \\ path";
const esc: string = s.replace(/(['"\\])/g, '\\$1');
console.log(esc); // He said \"It\'s a \\ path
console.log(esc.replace(/\\(['"\\])/g, '$1') === s); // true
Output
He said \"It\'s a \\ path
true

Language differences

C: hand-written escaping demos the three chars ' " \; C strings end at NUL, so an embedded NUL cannot be shown directly (PHP's \0 escape would need an explicit-length design in C).

C++: same as C, hand-written round trip; the std::string version skips buffer management.

C#: no built-in; parameterize SQL via the SqlCommand parameter collection (AddWithValue etc.) - concatenating into SQL text is injection bait.

Go: no built-in; database/sql parameterizes with ? placeholders.

Java: no built-in; the counterpart concept is PreparedStatement's ? placeholders - values stay separate from SQL text, so injection is impossible by construction.

JavaScript: no built-in; Node database drivers generally support parameterized queries.

PHP: addslashes handles only ' " \ and NUL, and the manual explicitly warns it does NOT prevent SQL injection (magic quotes was deprecated in PHP 5.3 and removed in 5.4); use prepared statements or driver-specific escaping (e.g. PDO::quote).

Python: no built-in; DB-API %s placeholders are escaped by the driver.

Rust: no built-in; bind query parameters.

TypeScript: same as JavaScript.