dslk6326846 2015-02-11 14:04
浏览 66
已采纳

错误:在PHP中的preg_match_all期间,无法在偏移错误处重复

I need to find if a file name contains some special characters I don't want.

I'm using this code actually:

$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.");
}

But I have an error saying:

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

Which is:

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

Any help or clue?

  • 写回答

2条回答 默认 最新

  • douyinyi7766 2015-02-11 14:16
    关注

    it is because ? * + are quantifiers. Since they are not escaped you obtain this error: |? there is obviously nothing to repeat.

    For your task you don't need to use an alternation, a character class should suffice:

    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);
    }
    

    or perhaps this pattern: ~[^[:alnum:]]~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致