正则表达式 - return 分割匹配

Regular expression - return split matches

我有代码:

<?php

$pattern = '~(?(?=hello 2)(hello 2)|hello (1))~';


$subjects = [];
$subjects[] = <<<EOD
test hello 2 test
EOD;


$subjects[] = <<<EOD
test hello 1 test
EOD;


$result = preg_match_all($pattern, $subjects[0], $matches);
assert($matches[1][0] == 'hello 2');

$result = preg_match_all($pattern, $subjects[1], $matches);
assert($matches[1][0] == '1');

我想要一个数组中的所有匹配项 - 数组中的 2 个项目(输入字符串,第一个或第二个表达式的结果),但现在我得到 3 个数组项(输入字符串,结果,空)或(输入字符串,空,结果)。在 var dump 中是:

实际状态:

array(3) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
  [1] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
  [2] =>
  array(1) {
    [0] =>
    string(0) ""
  }
}
array(3) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 1"
  }
  [1] =>
  array(1) {
    [0] =>
    string(0) ""
  }
  [2] =>
  array(1) {
    [0] =>
    string(1) "1"
  }
}

我要:

array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
  [1] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
}
array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 1"
  }
  [1] =>
  array(1) {
    [0] =>
    string(1) "1"
  }
}

您需要使用 分支重置?|:

$pattern = '~(?|(?=hello 2)(hello 2)|hello (1))~';

IDEONE demo

这样,您将避免非参与组出现在结果匹配数组中。

有关详细信息,请参阅 Branch Reset Groups 常规 expressions.info。