[英]Regular expression to remove anything but alphanumeric & spaces (in PHP)
I'm trying to remove, via regular expression, all but alphanumeric characters & spaces. 我试图通过正则表达式删除除字母数字字符和空格之外的所有字符。
Here's the conversion I am hoping to achieve. 这是我希望实现的转换。
"I am a string" → "I am a string"
"How are you?" → "How are you"
"#53-Jeff" → "53-Jeff"
So far I have this: 到目前为止我有这个:
return preg_replace("/[^0-9a-zA-Z]/","", $val);
But being a regex novice, I can't figure out how to insert a space. 但作为一个正则表达式的新手,我无法弄清楚如何插入空格。 I had odd results when I tried.
我尝试的时候结果很奇怪。
Inserting a space is just as simple as you expect it to be: 插入空格就像您期望的那样简单:
preg_replace("/[^0-9a-zA-Z ]/", "", $val);
Btw. 顺便说一句。 your third example is not clear to me: Do you want to replace the
-
too? 你的第三个例子对我来说不清楚:你想要替换
-
也是吗? If not, you need to add it to the character list too. 如果没有,您还需要将其添加到角色列表中。
This should work: 这应该工作:
preg_replace("/[^0-9a-zA-Z -]/", "", $val);
Keep in mind to add the "-" to the very end of the character set block, or it might get interpreted as a range operator. 请记住在字符集块的最后添加“ - ”,否则它可能会被解释为范围运算符。
Depending on your regex flags (if whitespace/comments are enabled) you might need to replace the " "
(right before the "-"
) with a "\\s"
or (stricter) "\\ "
. 根据你的正则表达式标志(如果启用了空格/注释),你可能需要用
"\\s"
或(更严格的) "\\ "
替换" "
(在"-"
之前)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.