PHP's htmlspeciachars不能处理单引号


PHP's htmlspeciachars not working on single quotes

我试图将单个报价转换为数据库插入的相关HTML代码,但它似乎不工作。当我创建以下脚本时:

<?php
 $str = "& and ' and '" and < and >";
 echo htmlspecialchars($str);
?>

我的浏览器返回以下内容:

&amp; and ' and &quot; and &lt; and &gt;

我做错了什么?我已经阅读了PHP手册上的htmlspecialchars()函数,它说它适用于单引号,但它似乎不适合我。

使用htmlentities()标记ENT_QUOTES。从手册:

ENT_QUOTES将转换双引号和单引号。

htmlentities($text, ENT_QUOTES);

如果您只想将'替换为&#39;,您当然可以使用str_replace():

str_replace("'", "&#39;", $text);

然而,由于您想要将数据插入SQL代码中,请查看PDO或MySQLi中的准备语句。这些函数服务于您所需要的确切目的(据我所知),并且将比您自己的函数更好。毕竟,为什么要重新发明轮子呢?

只是为了记录,请确保不要在PHP中使用已弃用的MySQL函数-如__为什么我不应该在PHP中使用mysql__* 函数.