用循环查找和替换许多单词

Find and replace many words with a loop

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

之前:

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在哪里声明? 然后在你的函数中,

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

应替换为

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

变量 $w 没有用,因为您对 $content 没有任何其他操作,只需覆盖它即可。此外,它会阻止您的功能正常工作,因为您仅在 $content 而不是 $w 中替换 return.

您需要将 $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);
}