php正则表达式之前和之后的特定单词

时间:2017-06-08 23:39:27

标签: php regex

我有一个包含如下数据的字符串:

$string = '
    foo=bar
    badge_name_foo=foo
    bar_badge_name=bar
    bar=baz
';

我希望匹配所有*_badge_namebadge_name_*字符串。

使用正则表达式是这样的: preg_match_all('~(?:(\w+)_)?badge_name(?:_(\w+))?~', $string, $matches, PREG_SET_ORDER);

结果是:

Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => 
            [2] => foo
        )

    [1] => Array
        (
            [0] => bar_badge_name
            [1] => bar
        )

)

*_badge_name工作正常,但在badge_name_*上每次都有空值?现在我如何使用preg_match_all

删除它

预期结果应为:

Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => foo
        )

    [1] => Array
        (
            [0] => bar_badge_name
            [1] => bar
        )

)

1 个答案:

答案 0 :(得分:1)

您似乎需要使用BRANCH RESET feature

  分支重置组内的

Alternatives共享相同的捕获组。语法为(?|regex),其中(?|打开组,regex为任何正则表达式。如果您不在分支重置组内使用任何交替或捕获组,则其特殊功能不起作用。然后它充当non-capturing group

使用

(?|(\w+)_badge_name|badge_name_(\w+))
^^^

请参阅regex demo

PHP demo

$re = '/(?|(\w+)_badge_name|badge_name_(\w+))/';
$str = 'foo=bar
badge_name_foo=foo
bar_badge_name=bar
bar=baz';
preg_match_all($re, $str, $matches);
print_r($matches);

结果:

Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => bar_badge_name
        )

    [1] => Array
        (
            [0] => foo
            [1] => bar
        )

)