当前位置:网站首页>php 转义字符串
php 转义字符串
2022-07-24 07:14:00 【whatday】
方法1:手动转义、还原字符串
字符串可以用单引号' '、双引号" "、定界符<<<3 种方式定义,其中最简单的方法就是使用单引号' '来定义字符串。当使用字符串时,字符串中很可能也需要使用这几个定义字符串的符号来作为字符串的一部分,为了避免混淆,就必须在这些符号的前面使用转移符\。
\是一个转义符,紧跟在\后面的第一个字符将变为没有意义或特殊意义的字符。例如,'是定义字符串的特殊符号,而写成\'后,就失去了它定义字符串的功能了,变为普通的单引号了。我们可以使用echo "\'";来输出一个单引号,转义符\不会显示。
【示例】使用转义字\对字符串进行转义。
<?php
header("Content-type:text/html;charset=utf-8");
echo 'Name:\'php中文网\'<br>Url:\'https://www.php.cn//\'';
?>运行结果如下:

对于简单的字符串,建议采用手动方法进行字符串转义,而对于数据量较大的字符串,建议采用自动转义函数实现字符串的转义。
2、自动转义、还原字符串
自动转义、还原字符串可以使用 PHP 提供的 addslashes() 函数和 stripslashes() 函数实现。
addslashes() 函数的作用是给字符串加入\,对指定的字符串进行转义,语法格式如下:
addslashes($str)addslashes() 函数返回的字符串中,为了数据库查询等语句的需要,会在某些字符前加上了反斜线,这些字符是单引号'、双引号"、反斜线\与 NULL。
stripslashes() 函数的作用是还原一个被转义的字符串,也就是去除在字符串中加入的反斜线,语法格式如下:
stripslashes($str)stripslashes() 函数会返回一个去除转义反斜线后的字符串(\'转换为',双反斜线\\被转换为单个反斜线\)。
【示例】使用 addslashes() 函数对字符串进行转义,然后使用 stripslashes() 函数进行还原。
<?php
header("Content-type:text/html;charset=utf-8");
$sql = "select * from php where website='php中文网'";
$str = addslashes($sql);
echo $str.'<br>';
$str = stripslashes($str);
echo $str;
?>运行结果如下:

边栏推荐
- AMD64(x86_64)架构abi文档:上
- Decompress the anchor and enjoy 4000w+ playback, adding a new wind to the Kwai food track?
- 周杰伦直播超654万人观看,总互动量破4.5亿,助力快手再破纪录
- numpy.concatenate
- 一个怎样的模式能让平台用户发生自助裂变?-链动2+1
- C language from entry to soil (III)
- 开发系统选择路线
- Redis sentinel mechanism
- 单点登录的三种实现方式
- Use dichotomy to find specific values from the array
猜你喜欢
随机推荐
Oauth2==SSO三种协议。Oauth2四种模式
拉普拉斯(Laplace)分布
Bookkeeping app: xiaoha bookkeeping 1 - production of welcome page
Can recursion still play like this? Recursive implementation of minesweeping game
C language from entry to soil (I)
libsvm 使用参数的基础知识笔记(1)
全国职业院校技能大赛网络安全B模块 Windows操作系统渗透测试
cookie_ session
变量和数据类型(04)完结
AMD64(x86_64)架构abi文档:上
单点登录的三种实现方式
C language from entry to Earth - array
Take you step by step to learn C (one)
Mongodb application scenario and model selection (massive data storage model selection)
File upload and download demo
研究会2022.07.22--对比学习
【LeetCode-简单】20. 有效的括号 - 栈
从CIA看常见网络攻击(爆破,PE,流量攻击)
17. 什么情况用ArrayList or LinkedList呢?
聚合型新生态模式-分享购,会员及奖励制度









