Regex PRCE PHP preg_match_all:如何删除匹配数组中的空节点?
$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
)
)
$text = 'Lorem Ipsum';
$re = '/(?<AA>Any)|(?<BB>Lorem)/ui';
$nMatches = preg_match_all($re, $text, $aMatches);
$aMatches
will contain the following:
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
)
)
Question:
Is it possible to return the array without nodes for named parts that have no matches?
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
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
特别是对于正则表达式,您可以看到 @Stephan 的回答。更一般地,当仅操作数组时,您可以使用 array_map 和 array_filter 来做到这一点。不带回调的
array_filter
将删除计算结果为false
的值(== false
不是=== false
,请参阅空)。对于单层数组:
对于二维数组:
Specifically for regex, you can see @Stephan's answer. More generally, when just manipulating arrays, you can use a combination of array_map and array_filter to do that.
array_filter
without a callback will strip the values that evaluates tofalse
(== false
not=== false
, see empty).For a single-level array:
For a 2D array:
您可以通过使用分支重置运算符来实现类似的效果:
/(?|(?Any)|(?Lorem))/ui
输出
通过使用此运算符,命名组必须具有相同的名称。
您测试正则表达式此处。
You can achieve something similar by using the branch-reset operator :
/(?|(?<BB>Any)|(?<BB>Lorem))/ui
outputs
By using this operator the named groups must have the same name.
You test the regexp here.