从数据库中获取一行并替换其中的一些内容

时间:2015-11-15 18:06:38

标签: php mysql mysqli str-replace

我需要从我的数据库中获取一行并替换其中的一些内容,但由于某些原因它不会被替换。我做错了什么?

来自数据库的行:

‘Shut up,’ ‘shut your mouth,’ and ‘be quiet' all mean to stop talking, but ‘be quiet' is nice. You don't want to be rude.

test.php:

include("connect.php"); //sql connection
include("functionsX.php"); //just some functions

$response = gd1("response/allData/where response like '%all mean to stop talking%'"); //get one row from database
echo $response."<br>";

$response = str_replace("&#8216;", "'", $response);
$response = str_replace("’", "'", $response);
echo $response;

结果:

‘Shut up,’ ‘shut your mouth,’ and ‘be quiet' all mean to stop talking, but ‘be quiet' is nice. You don't want to be rude.
'Shut up,’ 'shut your mouth,’ and 'be quiet' all mean to stop talking, but 'be quiet' is nice. You don't want to be rude.

需要结果:

‘Shut up,’ ‘shut your mouth,’ and ‘be quiet' all mean to stop talking, but ‘be quiet' is nice. You don't want to be rude.
'Shut up,' 'shut your mouth,' and 'be quiet' all mean to stop talking, but 'be quiet' is nice. You don't want to be rude.

2 个答案:

答案 0 :(得分:1)

似乎问题不应该是询问如何替换数据库输出中的奇数字符,而是如何防止它们首先出现在那里。

通常,当输出中有奇数字符时,表示您没有在数据库中设置正确的数据库字符集和排序规则。确保您的数据库,表格和列使用utf8_general_ciutf8_unicode_ci这样的字符集。我倾向于使用最后一个。

要了解两种排序规则之间的差异,请阅读此问题:What's the difference between utf8_general_ci and utf8_unicode_ci

您可以使用以下查询更改数据集和/或表的字符集和排序规则:

ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

或者你可以在PHPMyAdmin中做同样的事情,如下图所示:

enter image description here

您还应该告诉MySQLi使用UTF-8连接到数据库,如下所示:

$mysqli->set_charset("utf8");

您还可以告诉您的PHP页面输出UTF-8:

header('Content-Type: text/html; charset=utf-8');

当你保持字符集像这样对齐时,你不应该对像’之类的奇数字符有任何问题,然后你可以运行它:

html_entity_decode($str);

&#8216;等HTML实体转换为正确的含义,在本例中为'

答案 1 :(得分:0)

这对我有用:

$str = "&#8216;Shut up,’ &#8216;shut your mouth,’ and &#8216;be quiet' all mean to stop talking, but &#8216;be quiet' is nice. You don't want to be rude.";
$replacements = array('&#8216;', '’');
$nstr = str_replace($replacements, "'", $str);
echo $nstr;

请注意,str_replace()可以接受数组作为第一个参数(在我的情况下,$replacements)。那么可能是一个编码问题?什么时候保存回数据库?