PHP provides addslashes() and stripslashes() to escape and unescape special characters in strings. They are commonly used when dealing with quotes, backslashes, or user input before storing or displaying data.
addslashes(string) → returns escaped stringstripslashes(string) → returns original string
// Escaping quotes and special characters
<?php
$string = "He said, \"Hello, World!\"";
$escaped = addslashes($string);
echo $escaped;
?>
The addslashes() function inserts backslashes before double quotes, making the string safer for storage or processing.
// Removing escape characters from a string
<?php
$escaped = "He said, \"Hello, World!\"";
$unescaped = stripslashes($escaped);
echo $unescaped;
?>
stripslashes() restores the original readable string by removing added backslashes.
// Safely storing and retrieving user input
<?php
$userInput = "O'Reilly";
$escaped = addslashes($userInput);
$retrieved = stripslashes($escaped);
echo $retrieved;
?>
The output correctly displays: O'Reilly
Think of addslashes() as putting protective armor on quotes, and stripslashes() as removing that armor when it’s safe to display.
stripslashes() only when needed to avoid data loss.