我正在尝试从字符串中删除特殊字符。
用户在WYSWIG编辑器中输入文本,然后单击save,然后将数据保存到DB中。
但是,输入的是' (例如在单词don't中,脚本失败)。
我已经试过下面的方法了,但是没有用,有人能告诉我吗?
$content=$_POST[content];
function clean($content) {
$string = str_replace(' ', '-', $content); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $content); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
$result=mysql_query("update TABLE set content='$string' WHERE id='$id'");发布于 2015-08-06 10:11:44
您应该使用:http://php.net/manual/en/function.mysql-real-escape-string.php
,因为它将自动转义任何特殊字符并帮助防止SQL注入。
请注意页面上的大红横幅,它强烈建议不要使用MySQL,而应该使用MySQLi。
MySQLi的一个例子是:
$Sql = new MySQLi("localhost", "username", "password", "database_name");
$stmt = $Sql->prepare("UPDATE table SET content = ? WHERE id = ?");
$stmt->bind_param('si', $string, $id);
$stmt->execute();
$stmt->close();发布于 2015-08-06 10:16:07
有许多方法可以从字符串中删除不需要的字符。
addslashes()将在单引号和双引号之前添加斜杠,http://php.net/manual/en/function.addslashes.php htmlspecialchars()将将所有问题字符转换为html代码http://php.net/manual/en/function.htmlspecialchars.php。
最后,最重要的是,您的代码现在易受mysql注入的影响,以防止使用mysql_real_escape_string()删除可能导致http://php.net/manual/en/function.mysql-real-escape-string.php问题的所有字符。
您还应该考虑切换到MySQLi或PDO (我更喜欢PDO),因为有了它,您将得到准备好的语句,您将不会遇到这样的问题,也不会出现安全问题。MySQL是不推荐的,您的脚本在未来将无法工作。
https://stackoverflow.com/questions/31852884
复制相似问题