What is the addslashes() function in PHP

Overview

To use special symbols and characters as part of your string’s unpredictable behavior, you have to add backslashes just before the character.

You can either do this manually or by using the addslashes() function. The addslashes() function automatically adds backslashes to your string.

Syntax

addslashes($string);

Parameters

The function requires only one parameter which is the input string with characters to be escaped.

Support

This function is available in PHP version 4 and higher.

Return value

The function returns a string with escaped characters. These characters include:

  • Double quotes (")
  • Single quotes (')
  • Backslash (\)

Code

The code below shows the use of the addslashes() function:

<?php
$string=('"He said you cannot come "Home yet" with me"');
//escaping the variable $string;
$escString = addslashes($string);
//printing it to output
echo $escString."\n";
//escaping the $str
$str = addslashes('(\)\'');
// printing it to the screen
echo $str;
?>

Try not to use only this function for form input cleaning to prevent SQL injections.