如何使用 PHP 删除文本字段上的特殊字符和空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/2959877/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to I remove special characters and spaces on a textfield using PHP
提问by Benny
I need to remove all special characters and spaces on a textfield for a form I'm building. How do I accomplish this in PHP.
我需要删除我正在构建的表单的文本字段上的所有特殊字符和空格。我如何在 PHP 中完成此操作。
回答by Nicholas Kreidberg
This really depends, I assume you are working with $_POST[] data and wish to sanitize those inputs? If so I would definitely do something like:
这真的取决于,我假设您正在使用 $_POST[] 数据并希望清理这些输入?如果是这样,我肯定会做类似的事情:
$var = preg_replace("/[^A-Za-z0-9]/", "", $var);
That will strip out everything other than alpha/num, you can adjust the regex to include other characters if you wish. Some great examples of commonly used regular expressions can be found at: The RegEx Library
这将删除除字母/数字以外的所有内容,如果您愿意,您可以调整正则表达式以包含其他字符。可以在以下位置找到常用正则表达式的一些很好的示例:RegEx 库
If this isn't quite what you are looking for or have other questions let us know.
如果这不是您要查找的内容或有其他问题,请告诉我们。
回答by eykanal
Use the following regex during processing of the data:
在处理数据期间使用以下正则表达式:
$data = preg_replace('/[^A-Za-z0-9]/', "", $data);
This will remove all non-alphanumeric characters from the data.
这将从数据中删除所有非字母数字字符。
回答by Stijn Leenknegt
$specialChars = array(" ", "\r", "\n");
$replaceChars = array("", "", "");
$str = str_replace($specialChars, $replaceChars, $str);

