本文介绍了PHP Regex Word边界排除下划线_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式单词边界\ b,并且尝试在以下 $ sentence 中匹配 foo ,但结果不是我所需要的,下划线杀死了我,我希望下划线成为单词边界,就像连字符或空格一样:

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

预期:

$sentence = "foo_foo_foo foo-foo_foo";
             YES YES YES YES YES YES

我的代码:

preg_match("/\bfoo\b/i", $sentence);

推荐答案

您必须创建 DIY 边界.

You would have to create DIY boundaries.

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

这篇关于PHP Regex Word边界排除下划线_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 07:11