【问题标题】:Regular expression - return split matches正则表达式 - 返回拆分匹配
【发布时间】:2015-09-23 10:26:00
【问题描述】:

我有代码:

<?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"
  }
}

【问题讨论】:

  • 在这种简单的情况下,您可以将条件模式转换为分支重置~(?|(?=hello 2)(hello 2)|hello (1))~。如果这是更大模式的一部分(并且模式不是那么简单),那么您需要在第二个分支中重复条件,但是否定的。 ~(?|(?=hello 2)(hello 2)|(?!hello 2)hello (1))~
  • 完美,谢谢@nhahtdh。

标签: php regex preg-match-all


【解决方案1】:

您需要使用带有?|分支重置

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

IDEONE demo

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

有关更多详细信息,请参阅regular-expressions.info 上的Branch Reset Groups

【讨论】:

  • 很好,它工作得很好。你知道是否存在与 JavaScript 类似的东西吗?
  • :) 我知道几个后视解决方法和条件表达式解决方法,但至于分支重置......没有听说过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2011-03-06
相关资源
最近更新 更多