Home > Backend Development > PHP Tutorial > String operations in PHP (2)

String operations in PHP (2)

黄舟
Release: 2023-03-04 06:48:01
Original
1156 people have browsed it

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\&#39;m Tom";
    ?>
Copy after login

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&#39;m Tom";
    $str2 = addslashes($str);    //对字符串中的特殊字符进行转义    echo $str2 . "<br />";  
    echo stripslashes($str2);     //将转义后的字符串恢复,然后输出
    ?>
Copy after login

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);    //输出还原后的字符串
    ?>
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template