Home >Backend Development >PHP Problem >How to escape and anti-escape characters in php
In PHP, you can use the addslashes() function to escape characters, the syntax is "addslashes($str)"; you can use the stripslashes() function to reverse escape characters and restore an escaped character. A defined string with the syntax "stripslashes($str)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In PHP, you can use the addslashes() function and stripslashes() function to realize character escaping and anti-escaping.
1. addslashes() function
addslashes() function is to add \
to the string and convert the specified string. Definition, the syntax format is as follows:
addslashes($str)
Among them, $str
is the string to be escaped.
In the string returned by the addslashes() function, for the purpose of database queries and other statements, backslashes are added before certain characters. These characters are single quotes '
, Double quotes "
, backslashes \
and NULL
.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $sql = "select * from php where website='PHP中文网'"; $str = addslashes($sql); echo($str); ?>
2. Stripslashes() function
stripslashes() function is to restore an escaped string, that is, to remove the backslash added to the string. The syntax format is as follows:
stripslashes($str)
Among them, $str
is the string that needs to be restored.
stripslashes() function will return a character after removing the escaped backslash String (\'
is converted to '
, double backslash \\
is converted to single backslash \
).
Example:
<?php header("Content-type:text/html;charset=utf-8"); $sql = "select * from php where website=\'PHP中文网\'"; $str = stripslashes($sql); echo($str); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to escape and anti-escape characters in php. For more information, please follow other related articles on the PHP Chinese website!