PHP Tutorial - PHP addslashes() Function






Definition

There are many situations where single quotes ('), double quotes ("), and backslashes (\) can cause problems. Sometime we have to escape them with \, making \', \", and \\ respectively.

addslashes() function takes a string as its only parameter and returns the same string with these characters escaped.

Calling addslashes() repeatedly will add more and more slashes, like this:

Syntax

PHP addslashes() function has the folloiwng syntax.

string addslashes ( string str )

Parameter

str to add the slashes

Return

PHP addslashes() function returns the escaped string.





Note

In php.ini, magic_quotes_gpc option can set to enable "magic quotes". If enabled, PHP will automatically call addslashes() on every piece of data sent in from users.

Example 1


<?PHP
$string = "java2s.com's PHP tutorial"; 
$a = addslashes($string); 
$b = addslashes($a); 
$c = addslashes($b); 
?>

PHP will add a slash before each single and double quote, as well as slashes before every existing slash.

The addslashes() function has a counterpart, stripslashes(), that removes one set of slashes.

It is a good idea to use a database-specific escaping function instead of addslashes(). For example, if you're using MySQL, use mysql_escape_string().