PHP Regex Word Boundary exclude underscore _

白昼怎懂夜的黑 提交于 2021-02-04 15:45:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!