phpregexpcreword-boundary

Exclude underscore from word boundary in regex


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);

Solution

  • You would have to create DIY boundaries.

    (?:\b|_\K)foo(?=\b|_)