抱歉,如果这个问题已经得到回答,但我无法使用我的搜索查询找到答案,我不知道该怎么说。基本上,我正在构建一个单词过滤器,我正在从数据库表中获取单词,我正在使用 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.
"坏词"被过滤,但"测试"是附加到每个单词的附加广告。
我已经尝试过你的例子,并且此行似乎有错误
for($a=0;$a<=$i;$a++) {
应该是这样的
for($a=0;$a<$i;$a++) {