Mysql查询结果和str_replace

时间:2016-01-17 13:59:09

标签: php mysqli str-replace

我有以下代码:

<?php 
error_reporting(E_ALL);
set_time_limit(0); 

$source = ('Adam has a cat');
$db = new mysqli('localhost', 'root', 'pass', 'test') or die ('Not connect to MySQL.<br />Error: '.mysqli_error());
echo "Connect OK!<br />";
$db -> query("SET CHARSET utf8");
$db -> query("SET NAMES 'UTF-8' COLLATE 'utf8_polish_ci'");
$replace= "SELECT * FROM `replace`";
                $qr = $db->query($replace);
                while ($data = mysqli_fetch_assoc(qr))
            {
                $text= str_replace(($data['search']),($data['replace_new']),$source);
            }

echo ($text);

?>

我在数据库中有两列

search|replace_new

此列中的数据:

Adam|John
cat|dog

我想连接到db并将“Adam have a cat”替换为“John有一只狗”。

当我运行此代码时,只将Adam改为John,但cat不会改变。

有人知道我在这里做错了什么吗?任何帮助是极大的赞赏! 抱歉我的英文。

1 个答案:

答案 0 :(得分:0)

Oki是工作;)我发明了......;)

<?php 
error_reporting(E_ALL);
set_time_limit(0); 

$source = ('Adam has a cat');
$db = new mysqli('localhost', 'root', 'pass', 'test') or die ('Not connect to MySQL.<br />Error: '.mysqli_error());
echo "Connect OK!<br />";
$db -> query("SET CHARSET utf8");
$db -> query("SET NAMES 'UTF-8' COLLATE 'utf8_polish_ci'");
$replace= "SELECT * FROM `replace`";
                $qr = $db->query($replace);
                while ($data = mysqli_fetch_assoc(qr))
            {
                $source= str_replace(($data['search']),($data['replace_new']),$source);
            }

echo ($source);

?>