douweida2878 2013-11-28 10:51
浏览 3
已采纳

用于过滤扩展的格式正确的正则表达式是什么样的?

How to match 4 extensions with regexp?

I have tired this:

$returnValue = preg_match('/(pdf|jpg|jpeg|tif)/', 'pdf', $matches);

I dont know why I get 2 matches? I'm I something missed in the regexp?

array (
  0 => 'pdf',
  1 => 'pdf',
)
  • 写回答

1条回答 默认 最新

  • drsxobip501258 2013-11-28 10:51
    关注

    I dont know why I get 2 matches

    No you are getting only 1 match.

    $matches has 2 entries:

    1. 1st entry with index=0 is for the entire match of input by your regex
    2. 2nd entry with index=1 is for the first matched group since your regex is enclosed in parentheses

    If you want to avoid 2 entries you can use non-capturing group:

    $returnValue = preg_match('/(?:pdf|jpg|jpeg|tif)/', 'pdf', $matches);
    

    OR simply don't group them:

    $returnValue = preg_match('/pdf|jpg|jpeg|tif/', 'pdf', $matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?