2015-02-11 52 views
0

我需要找到一個文件名是否包含一些我不想要的特殊字符。錯誤:在PHP中的preg_match_all期間沒有重複的偏移量錯誤

我實際使用此代碼:

$files = array("logo.png", "légo.png"); 
$badChars = array(" ", "é", "É", "è", "È", "à", "À", "ç", "Ç", "¨", "^", "=", "/", "*", "-", "+", "'", "<", ">", ":", ";", ",", "`", "~", "/", "", "|", "!", "@", "#", "$", "%", "?", "&", "(", ")", "¬", "{", "}", "[", "]", "ù", "Ù", '"', "«", "»"); 
$matches = array(); 

foreach($files as $file) { 
    $matchFound = preg_match_all("#\b(" . implode("|", $badChars) . ")\b#i", $file, $matches); 
} 
if ($matchFound) { 
    $words = array_unique($matches[0]); 
    foreach($words as $word) { 
     $results[] = array('Error' => "Forbided chars found : ". $word); 
    } 
} 
else { 
    $results[] = array('Success' => "OK."); 
} 

但我有一個錯誤說:

Warning: preg_match_all(): Compilation failed: nothing to repeat at offset 38 in /home/public_html/upload.php on line 138 

那就是:

$matchFound = preg_match_all("#\b(" . implode("|", $badChars) . ")\b#i", $file, $matches); 

任何幫助或線索?

回答

2

這是因爲?*+是量詞。既然他們沒有逃脫,你會得到這個錯誤:|?顯然沒有什麼可重複的。

對於你的任務,你並不需要使用的交替,人物類應該足夠了:

if (preg_match_all('~[] éèàç¨^=/*-+\'<>:;,`\~/|[email protected]#$%?&()¬{}[ù"«»]~ui', $file, $m)) { 
    $m = array_unique($m[0]); 
    $m = array_map(function ($i) use ($file) { return array('Error' => 'Forbidden character found : ' . $i . ' in ' . $file); }, $m); 
    $results = array_merge($results, $m); 
} 

或許這種模式:~[^[:alnum:]]~

+0

得到了'解析錯誤:語法錯誤,意外' ,''爲你的第一行。 – poipoi 2015-02-11 14:20:52

+0

答案已經改變,刷新你的瀏覽器。 – 2015-02-11 14:21:46

+0

看起來不錯,但是我找到了'禁止發現的字符:數組',而我想'禁用的字符發現:+'例如。我該如何改變它? – poipoi 2015-02-11 14:24:21

1

這是因爲你的角色有*在裏面,它試圖重複前一個字符,在你的情況下,它最終是|,這是無效的。您正則表達式變成:

..... |/|*|-| ..... 

地圖preg_quote()到你的字符數組的循環之前,你會被罰款:

$badChars = array_map('preg_quote', $badChars); 

只要確保因爲你不指定在您的分隔符#致電preg_quote(),您必須在您的$badChars陣列中手動將其轉義。