\W+ 是什么意思?正则表达式中的意思?
我发现了这个:
$text = preg_replace('/\W+/', '-', $text);
谁能告诉我这到底是做什么的?没有关于 /\W+/
含义的信息。
I have found this:
$text = preg_replace('/\W+/', '-', $text);
Can anyone tell me what exactly this does? There is no information about what /\W+/
means.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
\W
表示非字母数字字符,即 az、AZ、0-9 或下划线以外的任何字符。这是正则表达式的标准,与 PHP 无关。
这是一个用于测试正则表达式的好工具:
http://www.gskinner.com/RegExr/
如果您将
\W+
放入顶部的框中,您将看到它匹配的内容类型。PS:这是另一个更简单、更干净的工具,尽管功能可能不那么丰富:
http://rubular.com/
它在底部包含一个方便的正则表达式快速参考。
\W
means a non-alphanumeric character, so anything other than a-z, A-Z, 0-9, or underscore.This is standard for regular expressions, nothing specific to Php.
Here's a great tool for testing regular expressions:
http://www.gskinner.com/RegExr/
If you put
\W+
in the box at the top you'll see what kinds of things it matches.PS: Here's another tool that's simpler and cleaner, though perhaps not as feature rich:
http://rubular.com/
It includes a handy quick-reference for regular expressions at the bottom.
看起来它替换了所有不是“单词字符”(字母、数字、下划线)的内容,并使它们成为连字符。
Looks like it replaces anything that isn't a 'word character' (letter, digit, underscore) and makes them hyphens.
preg
系列函数使用 Perl 兼容正则表达式 (PCRE)。这里有一个不错的备忘单 (PDF)。\W
表示“任何非单词字符”,+
将其限制为与一个或多个前面的字符匹配。 “单词字符”被定义为字母、数字和下划线,因此\W
将匹配不属于其中之一的字符。您的代码行将用连字符替换所有非单词字符的字符集。
The
preg
family of functions uses Perl Compatible Regular Expressions, or PCRE. There's a nice cheat sheet for them here (PDF).The
\W
means "any non word character", and the+
would limit it to matches of one or more of the preceding character. "Word characters" are defined to be letters, digits and underscores, so\W
would match characters that aren't one of those.Your line of code would replace any occurrence of a set of characters that aren't word characters with a hyphen.
如果您从 preg_replace() 的手册页开始,您可以单击 PCRE 获取有关正则表达式语法的全面文档。特别是,
\W
是一个 转义序列:If you start in the manual page for preg_replace(), you can click on PCRE to get comprehensive documentation about regular expression syntax. In particular,
\W
is a escape sequence: