【问题标题】:Find and replace many words with a loop用循环查找和替换许多单词
【发布时间】:2022-01-03 13:40:27
【问题描述】:

我有一个替换功能,因为要替换的单词很多,我想做一个循环,从数据库表中提取要替换的单词。我尝试编写代码,但没有成功。

之前:

function replaceString ($content){
    $w = str_replace("apple", "banana", $content);
    $w = str_replace("orange", "pear", $content);
    return $w;
}

之后:

function replaceString ($content){
    $Fruits = $mysqli->query("SELECT * FROM Fruits ORDER BY id DESC");

    while($row = mysqli_fetch_array($Fruits))){
        $content = str_replace($row['word'], $row['replace'], $content);
    }
    return $content;
}

【问题讨论】:

  • 实际发生了什么?您的查询是否有效?您的 $mysqli 数据库对象是否在范围内?每次调用str_replace 时都使用原来的$content 调用它,所以忘记之前的所有替换,这对吗?我认为 if() 子句也不需要 - 只需使用 while() 循环。
  • if(while()) 应该是什么样的构造? while 循环没有“返回值”。 if 没有位置,删除它并只是循环。
  • "BEFORE" 版本不起作用,因为在函数的第二行你需要替换 $w 而不是 $content: $w = str_replace("orange", "pear", $w );
  • 其实代码里没有“if”,我这里是加错的,为了不混淆,我把它去掉了。在任何情况下,代码都无法正常工作,函数不会出错,我只是不显示使用函数的字符串,实际上它返回空输出。
  • 您必须用引号将键括起来,否则 PHP 将假定这些是常量并抛出警告 Use of undefined constant word - assumed 'word'。您应该在开发过程中真正启用所有错误。 ini_set('display_errors', true); error_reporting(E_ALL); 这样你会看到 PHP 抛出警告

标签: php sql replace


【解决方案1】:

您需要将 $mysql 传递给您的函数:

<?php

function replaceString ($mysqli, $content){
    $Fruits = $mysqli->query("SELECT * FROM Fruits ORDER BY id DESC");

    while($row = mysqli_fetch_array($Fruits)) {
        $content = str_replace($row['word'], $row['replace'], $content);
    }
    return $content;
}

$string = 'An apple better then sugar, but orange not';


echo replaceString($mysqli, $string);

在此更改代码生效后。 PHP mysqli online here

结果

An banana better then sugar, but pear not

你也可以知道str_replace可以使用数组作为参数,所以你可以避免循环:

function replaceString ($mysqli, $content){
    $fruits = $mysqli->query("SELECT * FROM Fruits ORDER BY id DESC");
    
    $rows = $fruits->fetch_all(MYSQLI_ASSOC);
    
    return str_replace(array_column($rows, 'word'), array_column($rows, 'replace'), $content);
}

【讨论】:

    【解决方案2】:

    首先,$mysqli 声明在哪里? 然后在你的函数中,

       $w = str_replace($row[word], $row[replace], $content);
    

    应该替换为

       $content = str_replace($row[word], $row[replace], $content);
    

    变量$w 没有用,因为您对$content 没有任何其他作用,只需覆盖它即可。此外,它会阻止您的函数正常工作,因为您仅替换 $content 而不是您返回的 $w

    【讨论】:

    • 我做了,但它仍然不起作用。当我在字符串 replaceString($content) 上声明此函数时,不再显示。好像该函数有错误,如果我删除从数据库中提取数据的循环,它会完美运行。
    • 你看过@Darkbee 的评论吗?我没有注意到,但我猜应该引用 word 和 replace ?
    • $row[word] 应该会抛出明显的语法错误,除非您在任何地方定义了常量 wordreplace
    • @NicoHaase 我撤回了对这个答案的评论。似乎PHP&lt;8 只会发出通知,但会解释正确的索引 - demo
    猜你喜欢
    • 2012-01-04
    • 2012-10-27
    • 2015-04-21
    • 1970-01-01
    • 2019-10-23
    • 2014-07-26
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多