Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.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 - Fatal编程技术网

为字符串PHP制定特定规则

为字符串PHP制定特定规则,php,Php,我想清理用户的字符串输入。我想阻止特殊字符和代码符号,如,&等,但允许空格和单引号(')。到目前为止,我所做的是: $query = preg_replace('/[^A-Za-z0-9\-]/', '', htmlentities($request->search_name, ENT_COMPAT)); 当我使用上面的代码测试它时,它还删除了我需要的空格。非常感谢您的帮助 编辑: 如果我打字 mark O'neal"<>! 它应该输出: mark O'nealquotlt

我想清理用户的字符串输入。我想阻止特殊字符和代码符号,如
&
等,但允许
空格和
单引号(')
。到目前为止,我所做的是:

$query = preg_replace('/[^A-Za-z0-9\-]/', '', htmlentities($request->search_name, ENT_COMPAT));
当我使用上面的代码测试它时,它还删除了我需要的空格。非常感谢您的帮助

编辑:

如果我打字

mark O'neal"<>!
它应该输出:

mark O'nealquotltgt

您只需将空格和
字符添加到您的字符集:

$search_name = "mark O'neal\"<>!";
echo preg_replace("/[^A-Za-z0-9\- ']/", '', htmlentities($search_name, ENT_COMPAT));

您只需将空格和
字符添加到您的字符集:

$search_name = "mark O'neal\"<>!";
echo preg_replace("/[^A-Za-z0-9\- ']/", '', htmlentities($search_name, ENT_COMPAT));

忽略空格使用
\s

preg_replace('/[^A-Za-z0-9\-\s]/', ... );

忽略空格使用
\s

preg_replace('/[^A-Za-z0-9\-\s]/', ... );

不要那样做。相反,你需要学习如何正确编码文本。向我们展示你的输入和预期输出。我添加了我的输出预期。不要这样做。相反,你需要学习如何正确编码文本。向我们展示你的输入和预期输出我添加了我的输出预期,加上在那里做什么?你想忽略加号吗?是的,那也会忽略加号吗?如果你想忽略
+
符号,你可以使用
\s+
。加号在那里做什么?你也想忽略加号吗?是的,那也会忽略加号吗?如果你想忽略
+
符号,你可以使用
\s+