PHP addslashes()Function
Examples
Add a backslash before each double quote ("):
<?php
$str = addslashes('What does "yolo" mean?');
echo($str);
?>
$str = addslashes('What does "yolo" mean?');
echo($str);
?>
Run Example »
Definition and Usage
The addslashes() function returns a string with backslashes added before predefined characters.
The predefined characters are:
- Single quote (')
- Double quote (")
- Backslash (\)
- NULL
Tip:This function can be used to prepare appropriate strings for strings stored in the database and for database query statements.
Note:By default, the PHP directive magic_quotes_gpc is on, and it automatically runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped by magic_quotes_gpc, as this will cause double escaping. In this case, you can use the function get_magic_quotes_gpc() to detect it.
Syntax
addslashes(string)
| Parameter | Description |
|---|---|
| string | Required. Specifies the string to be escaped. |
Technical Details
| Return value: | Returns the escaped string. |
|---|---|
| PHP Version: | 4+ |
More Examples
Example 1
Add backslashes to predefined characters in a string:
<?php
$str = "Who's Peter Griffin?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";
?>
$str = "Who's Peter Griffin?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";
?>
Run Example »
PHP String Reference Manual Other Extensions