duanji7182 2013-08-12 07:10
浏览 66
已采纳

如何在preg_match_all结果中删除无用的数组项?

how to remove unuseful array items in preg_match_all result?

some of the items in the regex is not useful for me , I don't want them display in my $result array , how can I do it? I remmbered that preg_match can remove not useful "(xxx)" when get the result , but i don't remember how to code it now

<?php 

$url='http://www.new_pm.com/fr/lookbook/2.html';
preg_match_all('@([a-z]{2})?(lookbook)/?(\d+)?(\.html)?@',$url,$result);
print_r($result);

/* ------- 
Array
(
    [0] => Array
        (
            [0] => lookbook/2.html
        )

    [1] => Array    // I don't want $result has this item
        (
            [0] => 
        )

    [2] => Array
        (
            [0] => lookbook
        )

    [3] => Array
        (
            [0] => 2
        )

    [4] => Array    // I don't want $result has this item
        (
            [0] => .html
        )

)
 ------- */
?>
  • 写回答

1条回答 默认 最新

  • douchao1864 2013-08-12 07:36
    关注

    Every time you add parentheses into a pattern, that captures whatever was matched inside those parentheses and returns it in the result. Not only can this be annoying as in your case, it's also unnecessary overhead. For those reasons, whenever you don't actually need the result, either remove the parentheses (if possible) or use a non-capturing group (?:...) if you do need the grouping:

    @(?:[a-z]{2})?(lookbook)/?(\d+)?(?:\.html)?@
    

    Note that (\d+)? is the same as (\d*) (not in all cases and all flavors, but in your case it is):

    @(?:[a-z]{2})?(lookbook)/?(\d*)(?:\.html)?@
    

    Working demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?