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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分