PCRE matching whole words in a string
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/
精彩评论