PHP 字符串函数

PHP addslashes()函数用于返回带有斜杠的字符串,可以用来防止sql注入。它作用于以下这些预定义字符:

  • 单引号 (')
  • 双引号(")
  • 反斜杠(\)
  • NUL(不可见字符unicode)

语法

string addslashes (string $str);

参数

参数描述必须/可选
str要转义的字符串必须

返回值

返回转义后的字符串。

示例

介绍一些例子了解addslashes()函数的使用方法。

示例1

给双引号添加转义字符
<?php 
$str = 'What does "WHO" mean?';
echo addslashes($str); 
?> 

输出:

What does \"WHO\" mean?

示例2

给单引号增加转义字符
<?php
$str = "Who's the father of PHP?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";
?>

输出:

Who's the father of PHP? This is not safe in a database query.
Who\'s the father of PHP? This is safe in a database query.

示例3

带有反斜杠的例子

<?php
$str='\"php\"';
echo addslashes($str);
?>

输出:

\\\"php\\\"

说明一下为什么是3个斜杠,因为双引号需要一次转义,斜杠也需要一次转义,所以有3个斜杠。

示例4

看一个不可见字符的例子
<?php
$str =  "不可见unicode字符为: \u200b";
echo addslashes($str);
?> 

输出:

不可见unicode字符为: \\u200b