我需要检查字符串是否包含特定的单词。
我的代码如下:
// 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);