用于筛选扩展的格式良好的regexp是什么样子的


What does a well formatted regexp for filtering extensions look like?

如何将4个扩展与regexp匹配?

我已经厌倦了这个:

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

我不知道为什么我会得到2场比赛?我是正则表达式中遗漏了什么?

array (
  0 => 'pdf',
  1 => 'pdf',
)

I dont know why I get 2 matches

不,你只得到一场比赛。

$matches有两个条目:

  1. 1st entry with index=0用于正则表达式输入的整个匹配
  2. 2nd entry with index=1表示第一个匹配的组,因为正则表达式包含在括号中

如果你想避免两个条目,你可以使用non-capturing group:

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

或者干脆不分组:

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