Php 正则表达式-返回分割匹配
我有密码:Php 正则表达式-返回分割匹配,php,regex,preg-match-all,Php,Regex,Preg Match All,我有密码: <?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], $matche
<?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');
我想要:
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))~';
看
这样,您将避免非参与组作为结果匹配数组的一部分出现
有关更多详细信息,请参见regular-expressions.info。在这个简单的例子中,您可以将条件模式转换为分支重置
~(?|(?=hello 2)(hello 2)| hello(1))~
。如果这是一个更大的模式的一部分(并且该模式没有那么简单),那么您需要在第二个分支中重复该条件,但该条件是否定的<代码>~(?|)(?=hello 2)(hello 2)(hello 2)(hello 2)hello(1))~非常好,谢谢@nhahtdh.Nice,它工作得非常好。你知道是否存在类似于JavaScript的东西吗?:)我知道一些查找隐藏解决方法和条件表达式解决方法,但对于分支重置。。。没有听说过。