1

我在 MySQL 中有wordfilter表,我使用 PHP 从中获取所有行并在字符串中替换它们。

$string = "test string";
$result = mysqli_query($conn, "SELECT * FROM wordfilter;");
while ($row = mysqli_fetch_assoc($result))
{
    $string = str_replace($row['search'], $row['replace'], $string);
}

它将像这样工作:

Iteration number: (row from table) - result string
0: "tt string e"
1: ("tt", "<b>test</b>") - "<b>test</b> string e"
2: ("e", "f") - "<b>tfst</b> string f"
etc.

我希望它有这个结果"<b>test</b> string f"(“e”不替换为“f” <b>test</b>,因为它不存在于输入字符串中)。

4

1 回答 1

2

像这样构建一个搜索替换对数组:

$reps = array();
while($row = mysqli_fetch_assoc($result)) $reps[$row['search']] = $row['replace'];

然后使用strtr;的魔法

$string = strtr($string,$reps);
于 2013-03-02T00:35:14.597 回答