2010-01-24 48 views
3

我有一個函數可以加載它在wordpress上傳目錄中找到的所有圖像文件。我想稍微修改它,以便跳過任何以下劃線字符開頭的圖像,「_someimage.jpg」被略過,而「someimage.jpg不是...PHP正則表達式來查找以_開頭的圖像

這裏是現有的功能。 ...

$dir = 'wp-content/uploads/'; 
$url = get_bloginfo('url').'/wp-content/uploads/'; 
$imgs = array(); 
    if ($dh = opendir($dir)) 
    { 
    while (($file = readdir($dh)) !== false) 
    { 
    if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file)) 
    { 
    array_push($imgs, $file); 
    } 
    } 
    closedir($dh); 
    } else { 
    die('cannot open ' . $dir); 
    } 

回答

1

您可以修改當前的正則表達式或使用strstr(這我會建議)添加一個布爾表達式

修改當前的正則表達式:

"/^[^_].*\.(bmp|jpeg|gif|png|jpg)$/i" 

或簡單的表達式來檢測字符串中的下劃線是:

strstr($file, '_') 

編輯:實際上,你可以使用substr

substr($file, 0, 1) != '_' 
+0

'(bmp | gif | png | jpe?g |)' – 2010-01-24 02:19:08

+0

@Alix,從OP的原始表達式複製而來,現在編輯=) – 2010-01-24 02:20:32

+0

謝謝馬克!像魅力一樣工作:-) – 2010-01-24 15:05:43

0
if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file)) 

有可能轉化爲:

if (!is_dir($file) && preg_match("/^[^_].*\.(bmp|jpeg|gif|png|jpg|)$/i", $file)) 
+0

'(bmp | gif | png | jpe?g |)' – 2010-01-24 02:18:31

相關問題