Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 删除特殊字符_Php_Mysql - Fatal编程技术网

Php 删除特殊字符

Php 删除特殊字符,php,mysql,Php,Mysql,我正在尝试从字符串中删除特殊字符 用户将文本输入WYSWIG编辑器并单击保存,然后数据保存在数据库中 但是,如果输入了”(例如在单词中,不要脚本失败 我试过下面的方法,但不起作用,有人能给我建议吗 $content=$_POST[content]; function clean($content) { $string = str_replace(' ', '-', $content); // Replaces all spaces with hyphens. $string =

我正在尝试从字符串中删除特殊字符

用户将文本输入WYSWIG编辑器并单击保存,然后数据保存在数据库中

但是,如果输入了
(例如在单词
中,不要
脚本失败

我试过下面的方法,但不起作用,有人能给我建议吗

$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'");
你应使用:

因为它将自动转义任何特殊字符,并有助于防止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();

有许多方法可以从字符串中删除不需要的字符

addslashes()
将在单引号和双引号之前添加斜杠
htmlspecialchars()
将所有有问题的字符转换为html代码

最后,最重要的一点是,您的代码现在易受mysql注入攻击,以防止使用
mysql\u real\u escape\u string()
,这将删除所有可能导致问题的字符


您还应该考虑切换到MySQLi或PDO(我更喜欢PDO),因为有了它,您就可以得到准备好的语句,而且您永远不会有这样的问题,也不会有安全问题。MySQL已被弃用,您的脚本将来也不会工作。

使用addslashes()或htmlspecialchars(),另一个重要的命令是mysql\u real\u escape\u string,用于保护mysql不受mysql注入的影响。mysqli不会有这个问题:P@AleksandarVasić - Thanks@Zanderwar-你能告诉我如何使用MySqli来处理这个代码段吗?不要使用addslashes,你会留下不需要的斜杠,我可以向你保证。stripslashes()也会有意想不到的结果你可能是我需要和之交谈的人…你知道你的东西…我仍然是这方面的新手!!有很多比我更熟练的人,我已经根据要求为你更新了我的答案,并提供了一个MySQLi示例。如果它能帮你打勾的话,很酷;)