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.

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

报告相同问题?