php preg_replace在for循环错误期间追加和前置

时间:2014-11-29 12:57:27

标签: php regex for-loop filter preg-replace

很抱歉,如果这已经得到解答,但我找不到使用我的搜索查询的答案,我不知道怎么回事。基本上,我正在构建一个单词过滤器,我正在从db表中获取单词,我正在使用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.

过滤了“坏词”,但在每个词后附加了“test”广告。

1 个答案:

答案 0 :(得分:1)

我已经尝试过你的例子了,这一行似乎有错误

for($a=0;$a<=$i;$a++) {

应该是这样的

for($a=0;$a<$i;$a++) {