问题
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