An escape character is a special character constant.
The escape character starts with a backslash "", followed by one or more characters. Escape characters have specific meanings that are different from the original meaning of the characters, so they are called "escape" characters.
The use of escape characters
1: Convert ordinary characters to special purposes, such as back key, enter key, etc.
2: Used to convert characters with special meanings back to their original meanings.
3: Before data is written to the database, some sensitive characters will be escaped using escape characters (functions). Avoid website injection attacks.
Then during the PHP development project, we may encounter operations that require escaping a large amount of data.
Below we will introduce to you how to escape and restore strings in PHP through a simple code example.
1. Examples of using functions to escape strings
<?php
$str = "['name'=>'张三','age'=>19]";
echo $str . "<br>";
//对字符串进行转义
$a = addslashes($str);
//输出转义后的字符串
echo $a . "<br>";addslashes function: Use backslashes to quote strings.
The parameters represent the character data to be escaped. The return value is the escaped character.
In the above code, we define an array variable $str and use double single quotes to express it, and then use the addslashes function in PHP to escape.
We need to note here that we cannot use four double quotes, because then the system will not be able to parse the beginning and end of the string, and an error will occur.
2. Examples of using functions to restore strings
<?php
$str = "['name'=>'张三','age'=>19]";
echo $str . "<br>";
//对字符串进行转义
$a = addslashes($str);
//输出转义后的字符串
echo $a . "<br>";
//对转义后的字符串进行还原
$b = stripslashes($a);
//输出还原后的字符串
echo $b . "<br>";stripslashes function: dereference a quoted string.
The return value is a string with escaped backslashes removed (' converted to ', etc.).
Double backslashes (\) are converted to single backslashes ().
Here we mainly use the stripslashes function to restore the escaped string.