【发布时间】:2011-07-20 10:27:11
【问题描述】:
$text = 'Lorem Ipsum';
$re = '/(?<AA>Any)|(?<BB>Lorem)/ui';
$nMatches = preg_match_all($re, $text, $aMatches);
$aMatches 将包含以下内容:
Array (
[0] => Array (
[0] => Lorem
)
[AA] => Array ( // do not include to result matches array
[0] => // because have not match for this part
)
[1] => Array (
[0] =>
)
[BB] => Array (
[0] => Lorem
)
[2] => Array (
[0] => Lorem
)
)
问题: 对于没有匹配的命名部分,是否可以返回没有节点的数组?
Array (
[0] => Array (
[0] => Lorem
)
{there was [AA] && [1], but have not returned because empty}
[BB] => Array (
[0] => Lorem
)
[1] => Array ( // changed to 1
[0] => Lorem
)
)
【问题讨论】:
-
你至少可以用
$aMatches = array_filter($aMatches);清理它们 -
如果不返回正则表达式会更好。从结果数组中删除并不困难,但如果空节点不来自正则表达式会更好。
-
他们有不同的名字有什么原因吗?
-
@salathe:是的,这个正则表达式非常简化。实际上,我正在使用更多的命名组。
标签: php regex arrays pcre preg-match-all