【发布时间】:2014-11-29 12:57:27
【问题描述】:
很抱歉,如果这个问题已经得到解答,但我无法使用我的搜索查询找到答案,而且我不知道该怎么做。基本上,我正在构建一个单词过滤器,我正在从数据库表中获取单词,我正在使用 for 循环和 preg_replace 替换“坏词”,但“好词”被添加到每个字符串中的单词。这是我的代码:
$content = "The quick brown fox jumps over the lazy dog.";
// DB connection etc.
$bad = $row['bad_words'];
$good = $row['good_word']; // The "good word" for this example is "test"
$bad_words = explode(", ", $bad); // Let's say that "dog" is in the filter
$i = count($bad_words);
for($a=0;$a<=$i;$a++) {
$bad_words[$a] = str_replace(" ", "\s?", $bad_words[$a]); // I'm checking for a space, not sure if this bit is correct (\s?). Can I use the question mark in this case?
$content = preg_replace("/".$bad_words[$a]."\b/i", $good, $content);
}
结果是:
testThetest testquicktest testbrowntest testfoxtest testjumpstest testovertest testthetest testlazytest testtesttest.
“坏词”被过滤,但“测试”被附加到每个词的前面。
【问题讨论】:
标签: php regex for-loop filter preg-replace