【发布时间】: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