There are two ways to escape and restore strings: one is to manually escape and restore string data, and the other is to automatically escape and restore string data.
1. Manually escape and restore string data
Strings can be defined in three ways: single quotes ('), double quotes (""), and delimiters ({}). When using a string, it is likely that there are characters in the string that confuse these symbols with PHP scripts, so escape statements must be made. This requires adding the escape symbol "" in front of it.
"" is an escape character, and the characters immediately following "" will become meaningless.
For example:
<?php echo "I\'m Tom"; ?>
The running result is: I'm Tom.
2. Automatic escaping and restoration of string data
Automatic escaping and restoration of string data can be achieved by applying the addslashes() function and stripslashes() function provided by PHP. The
addslashes() function is used to add slashes "" to strings.
The stripslashes() function is used to restore the string escaped using the addslashes() function.
For example:
<?php $str = "I'm Tom"; $str2 = addslashes($str); //对字符串中的特殊字符进行转义 echo $str2 . "<br />"; echo stripslashes($str2); //将转义后的字符串恢复,然后输出 ?>
Running result:
I'm Tom
I'm Tom
The above two functions realize automatic escaping and restoration of the specified string. In addition to the methods introduced above, you can also limit the range of strings to be escaped and restored. By using the addcslashes() function and stripcslashes() function, you can automatically escape and restore strings within the specified range. The
addcslashes() function implements escaping characters in a string, that is, adding a backslash before the specified string.
The stripcslashes() function is used to restore strings escaped using the addcslashes() function.
For example:
<?php $str = "自学PHP就上PHP中文网"; $str2 = addcslashes($str, "自学PHP就上PHP中文网"); echo $str2 . "<br />"; //输出转义后的字符串 echo stripcslashes($str2); //输出还原后的字符串 ?>
Run result:
327324321247PHP276315311317321247260311315370
Teach yourself PHP on the PHP Chinese website
That’s it Contents of string operations (2), please pay attention to the PHP Chinese website for more related content (www.php.cn)!