string addslashes ( string $string )
$string: The input string where special characters will be escaped by backslashes.$str = "John's book";
echo addslashes($str); // Output will add backslashes before the single quote
Output:
John\'s book
$str = 'He said, "It\'s a test!"';
echo addslashes($str); // Backslashes added before single and double quotes
Output:
He said, \"It\'s a test!\"
$str = "C:\\Program Files\\";
echo addslashes($str); // No additional backslashes
Output:
C:\\Program Files\\
$str = "A NULL character \0 is here.";
echo "Output with echo: " . $str . "<BR>"; // The output will end after the NULL character
// To display the full string, including the escaped NULL, we use var_dump
var_dump(addslashes($str));
Output:
Output with echo: A NULL character
string(28) "A NULL character \0 is here."
As you can see, the addslashes() function adds a backslash before the NULL character, but the regular `echo` only prints up to the NULL character. Using var_dump(), we can see the full string including the escaped NULL.
$name = "O'Reilly";
$sql = "SELECT * FROM users WHERE name = '" . addslashes($name) . "'";
echo $sql;
Output:
SELECT * FROM users WHERE name = 'O\'Reilly'
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.