PHP preg_match 查找整个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4722007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:08:40  来源:igfitidea点击:

PHP preg_match to find whole words

phppreg-match

提问by tintix

I'm quite new to regular expressions. Could you help me to create a pattern, which matches whole words, containing specific part? For example, if I have a text string "Perform a regular expression match" and if I search for express, it shuld give me expression, if I search for form, it should give me Performand so on. Got the idea?

我对正则表达式很陌生。你能帮我创建一个模式,匹配整个单词,包含特定部分吗?例如,如果我有一个文本字符串“执行正则表达式匹配”,并且如果我搜索express,它应该给我expression,如果我搜索form,它应该给我Perform等等。明白了吗?

回答by Linus Kleen

preg_match('/\b(express\w+)\b/', $string, $matches); // matches expression
preg_match('/\b(\w*form\w*)\b/', $string, $matches); // matches perform,
                                                     // formation, unformatted

Where:

在哪里:

  • \bis a word boundary
  • \w+is one or more "word" character*
  • \w*is zero or more "word" characters
  • \b是一个词边界
  • \w+是一个或多个“单词”字符*
  • \w*是零个或多个“单词”字符

See the manual on escape sequencesfor PCRE.

请参阅有关PCRE转义序列的手册。



* Note: although not really a "word character", the underscore _is also included int the character class \w.

* 注意:虽然不是真正的“单词字符”,但下划线_也包含在字符类中\w

回答by Kyle Wild

This matches 'Perform':

这与“执行”匹配:

\b(\w*form\w*)\b

This matches 'expression':

这匹配“表达式”:

\b(\w*express\w*)\b