开发者

PCRE matching whole words in a string

开发者 https://www.devze.com 2023-04-10 16:25 出处:网络
I\'m trying to run a regexp in ph开发者_运维百科p (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.

I'm trying to run a regexp in ph开发者_运维百科p (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"


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.


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

/testable|string/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号