我需要查找文件名是否包含一些我不想要的特殊字符。
我实际上使用的是这个代码:
$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);
有什么帮助或线索吗?
?
*
+
是量词。由于它们没有逃脱,所以您获得了这个错误:|?
,显然没有什么可重复的。
对于您不需要使用交替的任务,一个字符类就足够了:
if (preg_match_all('~[] éèàç¨^=/*-+''<>:;,`'~/|!@#$%?&()¬{}[ù"«»]~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:]]~
这是因为你的字符中有*
,它试图重复前一个字符,在你的情况下,它最终是|
,这是无效的。您的正则表达式变为:
..... |/|*|-| .....
在循环之前将preg_quote()
映射到你的字符数组,你就可以了:
$badChars = array_map( 'preg_quote', $badChars);
只需确保,由于在对preg_quote()
的调用中没有指定分隔符#
,因此必须在$badChars
数组中手动转义它。