Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - addslashes() Function



The PHP addslashes() function is used to escape the special character such as single quotes (''), double quotes (""), backslashes("\), and NULL characters (\0) from the given string.

This function returns the escaped string (quote string) with backslashes added before the special characters that need to be escaped.

To escape a specific character in a given string, the PHP provides another function named addcslashes() function.

Syntax

Following is the syntax of the PHP addslashes() function −

addslashes(string $str): string

Parameters

This function accepts a single parameter, which is described below −

  • str − This string to be escaped.

Return Value

This function returns the escaped string.

Example 1

Escaping the single quote (') special character from a string.

The following is a basic example of the PHP addslashes() function −

<?php
   $str = "Tutorials'point";
   echo "The given string is: $str";
   #using addslashes() function
   echo "\nThe escaped string: ".addslashes($str);
?>

Output

The above program produces the following output −

The given string is: Tutorials'point
The escaped string: Tutorials\'point

Example 2

Escaping the double quote (") special character from a string.

Here is another example of the PHP addslashes() function. We use this function to retrieve an escaped string by escaping all the double (") quote characters in the string 'Welcome to "Tutorialspoint"' −

<?php
   $str = 'Welcome to "Tutorialspoint"';
   echo "The given string is: $str";
   #using addslashes() function
   echo "\nThe escaped string: ".addslashes($str);
?>

Output

After executing the above program, the following output will be displayed −

The given string is: Welcome to "Tutorialspoint"
The escaped string: Welcome to \"Tutorialspoint\"

Example 3

Escaping the NULL character (\0) from a string:

The following is an example of how to use the PHP addslashes() function to escape the NULL character from a string −

<?php
   $str = "Hello World\0";
   echo "The given string is: $str";
   #using addslashes() function
   echo "\nThe escaped string: ".addslashes($str);
?>

Output

Once the above program is executed, it generates the following output −

The given string is: Hello World
The escaped string: Hello World\0
php_function_reference.htm
Advertisements