2008-11-26 106 views
15

我正在阅读单个目录中的所有文件,并且我想过滤JPG,JPEG,GIF和PNG。使用正则表达式检查PHP中的文件扩展名

都是大小写字母。这些是唯一被接受的文件。我目前正在使用这个

$testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)"); 

和功能takeFiles看起来是这样的:

function takerFiles($dir, $rex="") { 
    $dir .= "/"; 
    $files = array(); 
    $dp = opendir($dir); 
    while ($file = readdir($dp)) { 
     if ($file == '.') continue; 
     if ($file == '..') continue; 
     if (is_dir($file)) continue; 
     if ($rex!="" && !preg_match($rex, $file)) continue; 
     $files[] = $file; 
    } 
    closedir($dp); 
    return $files; 
    } 

,它始终没有返回。所以,我的正则表达式代码肯定有问题。

回答

30

我认为你的正则表达式有问题。尝试在这里第一次测试的正则表达式:​​

我觉得这个可能会为你工作:

/^.*\.(jpg|jpeg|png|gif)$/i

注意/我在最后 - 这是“不区分大小写”标志,可以节省你不必输出所有排列组合:)

+1

你必须逃脱点。 – Mark 2008-11-26 15:50:33

+1

谢谢马克,修好了。 D'哦! – 2008-11-26 15:55:47

+0

@PhillSacre到SpawEditor的链接已过期。你能否更新你的答案? – 2016-12-22 10:56:47

1

你应该把你的正则表达式的斜杠。 - >“/(...)/”

11

如何用glob()代替?

$files = glob($dir . '*.{jpg,gif,png,jpeg}',GLOB_BRACE); 
0

有几种方法可以做到这一点。

你试过glob()

$files = glob("{$picsDir}/*.{gif,jpeg,jpg,png}", GLOB_BRACE); 

你有没有考虑pathinfo()

$info = pathinfo($file); 
switch(strtolower($info['extension'])) { 
    case 'jpeg': 
    case 'jpg': 
    case 'gif': 
    case 'png': 
     $files[] = $file; 
     break; 
} 

如果你在使用正则表达式insistant,就没有必要将整个文件名匹配,只是扩展。使用$标记来匹配字符串的末尾,并使用i标志来表示不区分大小写。另外,不要忘了在表达式中使用的分隔符,在我的情况下,“%”:

$rex = '%\.(gif|jpe?g|png)$%i'; 
2

有你不想使用scandirpathinfo任何理由?

public function scanForFiles($path, array $exts) 
{ 
    $files = scanDir($path); 

    $return = array(); 

    foreach($files as $file) 
    { 
     if($file != '.' && $file != '..') 
     { 
      if(in_array(pathinfo($file, PATHINFO_EXTENSION), $exts))) { 
       $return[] = $file; 
      } 
     } 
    } 

    return $return; 
} 

因此,您还可以检查文件是否是目录并执行递归调用来扫描该目录。我匆忙编写代码,因此可能不是100%正确的。

1

这工作我出去

$string = "your-file-name.jpg"; 
preg_match("/\b(\.jpg|\.JPG|\.png|\.PNG|\.gif|\.GIF)\b/", $string, $output_array); 

最佳。

0

以下是根据目标目录的类型(conf for demo)编译文件数组的两种不同方式。我不确定哪个性能更好。

$path = '/etc/apache2/'; 
    $conf_files = []; 

    // Remove . and .. from the returned array from scandir 
    $files = array_diff(scandir($path), array('.', '..')); 
    foreach($files as $file) { 
     if(in_array(pathinfo($file, PATHINFO_EXTENSION), ['conf'])) { 
      $conf_files[] = $file; 
     } 
    } 
    return $conf_files; 

这将返回完整的文件路径不只是文件名

return $files = glob($path . '*.{conf}',GLOB_BRACE); 
相关问题