问题
I'm using regex word boundary \b, and I'm trying to match foo
in the following $sentence
but the result is not what I need, the underscore
is killing me, I want underscore to be word boundary just like hyphen or space:
$sentence = "foo_foo_foo foo-foo_foo";
X X X YES X X
Expected:
$sentence = "foo_foo_foo foo-foo_foo";
YES YES YES YES YES YES
My code:
preg_match("/\bfoo\b/i", $sentence);
回答1:
You would have to create DIY boundaries.
(?:\b|_\K)foo(?=\b|_)
回答2:
Does this do what you want?:
preg_match_all("/foo/i", $sentence, $matches);
var_dump($matches);
来源:https://stackoverflow.com/questions/29068664/php-regex-word-boundary-exclude-underscore