使用正则表达式删除字母数字&以外的任何内容空格(在PHP中) [英] Regular expression to remove anything but alphanumeric & spaces (in PHP)

查看:187
本文介绍了使用正则表达式删除字母数字&以外的任何内容空格(在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.

有关运行示例,请参见.

See this for a running example.

这篇关于使用正则表达式删除字母数字&以外的任何内容空格(在PHP中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆