PCRE matching whole words in a string

廉价感情. 提交于 2019-12-19 19:13:52

问题


I'm trying to run a regexp in php (preg_match_all) that matches certain whole words in a string, but problem is that it also matches words that contain only part of a tested word. Also this is a sub-query in a larger regexp, so other PHP functions like strpos won't help me, sadly.

String: "I test a string"

Words to match: "testable", "string"

Tried regexp: /([testable|string]+)/

Expected result: "string" only!

Result: "test", "a", "string"


回答1:


If you really want to make sure you only get your words and not words that contain them, then you can use word boundary anchors:

/\b(testable|string)\b/

This will match only a word boundary followed by either testable or string and then another word boundary.




回答2:


You don't want a character class with [], you just want to match the words:

/testable|string/



来源:https://stackoverflow.com/questions/7662628/pcre-matching-whole-words-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!