2015-02-11 49 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阵列中手动将其转义。