在PHP中进行预匹配时出错
我需要检查字符串是否包含特定的单词 我的代码如下:在PHP中进行预匹配时出错,php,preg-match,Php,Preg Match,我需要检查字符串是否包含特定的单词 我的代码如下: // Get index.html source $html = file_get_contents('extract/index.html'); // Bad words checker $badWords = array("iframe", "alert"); $matches = array(); $matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i"
// Get index.html source
$html = file_get_contents('extract/index.html');
// Bad words checker
$badWords = array("iframe", "alert");
$matches = array();
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $html, $matches);
if ($matchFound) {
$words = array_unique($matches[0]);
foreach($words as $word) {
$results[] = array('Error' => "Keyword found : ". $word);
}
}
else {
$results[] = array('Success' => "No keywords found.");
}
每次执行此操作时,我都会收到以下警告:
Warning: preg_match_all(): Unknown modifier 'w' in /home/public_html/upload.php on line 131
第131行:
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $html, $matches);
你知道为什么吗
谢谢。如果其中一个不好的词是“/w”,它可能会导致此问题。下面的例子说明了这一点:
$html = 'foobar';
// Bad words checker
$badWords = array("iframe", "alert", '/w');
$matches = array();
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $html, $matches);
“/w”的变体,如“foo/wbar”或“/wfoo”也会导致此问题。仔细检查那些坏话,去掉那些有问题的
编辑:另一种解决方案是使用不同的分隔符,如#。像这样:
$matchFound = preg_match_all("#\b(" . implode($badWords,"|") . ")\b#i", $html, $matches);
更新您的代码,以便您可以输出正则表达式,并查看它在运行时的实际情况。
内爆($badWords,“|”)
是问题所在。注意:由于历史原因,内爆()可以按任意顺序接受其参数。但是,为了与explode()保持一致,使用有文档记录的参数顺序可能会更容易混淆。
var\u dump your intlode($baddwords,“|”)file\u get\u html()
不是PHP内置函数@开放调谐-你明白了!我马上就接受你的回答!谢谢