PHP 中的 preg_replace - NOT 条件的正则表达式
我正在尝试使用 preg_replace 在 PHP 中编写一个函数,它将替换列表中未找到的所有字符。通常我们会替换它们所在的位置,但这个不同。
例如,如果我有字符串:
$mystring = "ab2c4d";
我可以编写以下函数,它将用 * 替换所有数字:
preg_replace("/(\d+)/","*",$mystring);
但我想替换从 a 到 z 的那些既不是数字也不是字母的字符。它们可以是类似 #$*();~!{}[]|\/.,<>?'等等
所以除了数字和字母之外的任何东西都应该被其他东西代替。我该怎么做?
谢谢
I am trying to write a function in PHP using preg_replace where it will replace all those characters which are NOT found in list. Normally we replace where they are found but this one is different.
For example if I have the string:
$mystring = "ab2c4d";
I can write the following function which will replace all numbers with *:
preg_replace("/(\d+)/","*",$mystring);
But I want to replace those characters which are neither number nor alphabets from a to z. They could be anything like #$*();~!{}[]|\/.,<>?' e.t.c.
So anything other than numbers and alphabets should be replaced by something else. How do I do that?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用否定字符类(使用
^
在课程的开头):更新: 我的意思是,您必须使用否定的字符类,并且您可以使用我提供的,但还有其他的;)
You can use a negated character class (using
^
at the beginning of the class):Update: I mean, you have to use a negated character class and you can use the one I provided but there are others as well ;)
尝试
Try
您想要使用否定的“字符类”。它们的语法是
[^...]
。在你的情况下,我认为只是[^\w]
。You want to use a negated "character class". The syntax for them is
[^...]
. In your case just[^\w]
I think.\W
匹配非字母、非数字字符。下划线_
包含在字母数字列表中,因此这里也不会匹配。如果您可以忍受下划线不被替换,应该这样做。如果不能,请使用
\W
matches a non-alpha, non-digit character. The underscore_
is included in the list of alphanumerics, so it also won't match here.should do if you can live with the underscore not being replaced. If you can't, use
正则表达式中的
\d
、\w
和类似的都有负版本,它们只是同一字母的大写版本。因此
\w
匹配任何单词字符(即基本上字母数字),因此\W
匹配除单词字符之外的任何内容,因此除了字母数字之外的任何内容。这听起来像是你所追求的。
有关更多信息,我推荐 regular-expressions.info。
The
\d
,\w
and similar in regex all have negative versions, which are simply the upper-case version of the same letter.So
\w
matches any word character (ie basically alpha-numerics), and therefore\W
matches anything except a word character, so anything other than an alpha-numeric.This sounds like what you're after.
For more info, I recommend regular-expressions.info.
由于 PHP 5.1.0 可以使用
\p{L}
(Unicode 字母)和\p{N}
(Unicode 数字),这与\d 等价于 unicode
和\w
表示拉丁语preg_replace("/[^\p{L}\p{N}]/iu", $replacement_string, $original_string);
模式末尾的
/iu
修饰符:i (PCRE_CASELESS)
u (PCRE_UTF8)
查看更多信息: https://www.php.net/手册/en/reference.pcre.pattern.modifiers.php
Since PHP 5.1.0 can use
\p{L}
(Unicode letters) and\p{N}
(Unicode digits) that is unicode equivalent like\d
and\w
for latinpreg_replace("/[^\p{L}\p{N}]/iu", $replacement_string, $original_string);
/iu
modifiers at the end of pattern:i (PCRE_CASELESS)
u (PCRE_UTF8)
see more at: https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php