【问题标题】:php preg_replace appending and prepending during for loop errorphp preg_replace 在for循环错误期间追加和前置
【发布时间】: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


    【解决方案1】:

    我试过你的例子,这行似乎有错误

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

    应该是这样的

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

    【讨论】:

      猜你喜欢
      • 2013-09-22
      • 2013-03-09
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      相关资源
      最近更新 更多