PHP addslashes function – Quote string with slashes

Description

There are many situations where single quotes (‘), double quotes (“), and backslashes (\) can cause problems—databases, files, and some protocols require that you escape them with \, making \’, \”, and \\ respectively. In these circumstances, you should use the addslashes() function, which takes a string as its only parameter and returns the same string with these offending characters escaped so that they are safe for use. The stripslashes() function is the inverse for this function.

Syntax:

addslashes(string $string): string

Parameters

Parameter Description
string The string to be escaped.

Return Values

Returns the escaped string.

Examples

Example 1: A use case of addslashes() is escaping the aforementioned characters in a string that is to be evaluated by PHP:

<?php
$str = "Let's try this";
eval("echo '" . addslashes($str) . "';");
?>

Example 2

<?php
$hello=”Are you Jack’s brother?”; 
echo addslashes($hello);
?>

The output of the above program is:

Are you Jack\’s brother?
Note: If you can, use a database-specific escaping function instead of addslashes(). For example, if you’re using MySQL, use mysql_escape_string().
Related Post