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);
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”.
The \b metacharacter matches at the beginning or end of a word.
Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .
You would have to create DIY boundaries.
(?:\b|_\K)foo(?=\b|_)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With