Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex Word Boundary exclude underscore _

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);
like image 215
Sunny Avatar asked Mar 16 '15 02:03

Sunny


People also ask

Is underscore a word boundary?

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

What characters are word boundaries in regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”.

What does \b mean in regular expressions?

The \b metacharacter matches at the beginning or end of a word.

What is the difference between \b and \b in regular expression?

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 .


1 Answers

You would have to create DIY boundaries.

(?:\b|_\K)foo(?=\b|_)
like image 136
hwnd Avatar answered Sep 17 '22 22:09

hwnd