Heim  >  Artikel  >  Backend-Entwicklung  >  PHP特殊字符如反斜杠处理函数addslashes()和stripslashes()的用法

PHP特殊字符如反斜杠处理函数addslashes()和stripslashes()的用法

WBOY
WBOYOriginal
2016-06-20 13:03:201153Durchsuche

PHP自带的库函数 addslashes() 和 stripslashes() 都属于字符串处理类函数,作用正好相反:

addslashes():对输入字符串中的某些预定义字符前添加反斜杠,这样处理是为了数据库查询语句等的需要。这些预定义字符是:单引号 (') ,双引号 (") ,反斜杠 (\) ,NULL。

stripslashes():删除由 addslashes() 函数添加的反斜杠。该函数用于清理从数据库或 HTML 表单中取回的数据。(若是连续二个反斜杠,则去掉一个,保留一个;若只有一个反斜杠,就直接去掉。)

ps:默认情况下,PHP 指令 magic_quotes_gpc 为 on,对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。例:

if (get_magic_quotes_gpc()){
      code....
}

addslashes() 例子:

<?php
$str = "Who&#39;s John Adams?";
echo $str . " This is not safe in a database query.<br />";
echo addslashes($str) . " This is safe in a database query.";
?>

输出:

Who's John Adams? This is not safe in a database query.
Who\'s John Adams? This is safe in a database query.

stripslashes() 例子:

<?php
echo stripslashes("Who\&#39;s John Adams?");
?>

输出:

Who's John Adams?


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn