使用正则表达式替换 PHP 中字符串中的特殊字符(某些字符除外)
我想替换字符串中除空格和 - 之外的所有特殊字符。
例如,
Hello-my name *is (Jämes93!
到
Hello-my name is James93
甚至
Hello-my nme is Jmes93
我有以下内容,但它不起作用。请有人帮忙吗? 谢谢
preg_replace('#[^\w-]#',"",$string)
I would like to replace all special characters in a string except space and -.
For example,
Hello-my näme *is (Jämes93!
to
Hello-my name is James93
or even
Hello-my nme is Jmes93
I have the following but it won't work. Pls can someone help?
Thanks
preg_replace('#[^\w-]#',"",$string)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不想对这些使用正则表达式。使用
iconv()
效果会更好与 音译:
假设原始字符串是用
编码的UTF-8
并且您想将其转换为ASCII
这接近您的问题。只要您知道原始字符集,就可以以相同的方式与其他字符集进行转换。
顺便说一下,你不能使用
preg_replace
来做到这一点,它不支持 < em>音译。You don't want to use regex for these. You are much better off using
iconv()
with transliteration:
This assumes that original string is encoded in
UTF-8
and you want to convert it toASCII
which comes close to your question.You can convert to/from other charsets the same way just as long as you know the original charset.
By the way, you can't do that with
preg_replace
, it does not support transliteration.只是为了回答您的具体问题,您的代码的问题是 preg_replace 实际上并没有更改字符串。您需要将结果分配回 $string。
Just to answer your specific question, the problem with your code is that preg_replace doesn't actually change the string. You need to assign the result back to $string.
有几种方法可以做到这一点:
第一种方法:
第二种方法:
但第二种方法不会替换所有特殊字母。我更喜欢你使用第一个。
希望这对您有帮助。
There are several ways to do it:
First method:
Second method:
But second method will not replace all the special alphabets. I prefer you to use first one.
Hope this helps you.
您可以使用如下代码:
输出:
You can use code like this:
OUTPUT: