【问题标题】:str_replace PHP doesn't workstr_replace PHP 不起作用
【发布时间】:2015-07-22 20:03:17
【问题描述】:

我正在尝试用其他字符串替换某些字符 我用这个确切的代码让它在我的主页上工作,但在另一个页面上它不会工作。

在数据库中我得到了这个±1¢2£¥3§4£description2 在我的 php 中,我使用

$description2 = mysql_result($product, 0, 'productDescription2');

if ($description2 !=""){
$searchArray = array('±', '¢', '£', '¥', '§');
$replaceArray = array('x', 'x', 'x', 'x', 'x');
$teknisk =  str_replace($searchArray, $replaceArray, $description2);}

作为输出我使用echo ''. $teknisk .'';

但是结果是这个�1�2��3�4�(和原来的description2一样)

而不是x1x2xx3x4x

请帮忙!

【问题讨论】:

  • 我认为这是由于您的数据库中的编码。我试过你的脚本,当$description2 = "±1¢2£¥3§4£"
  • 您可以使用 phpMyAdmin 或通过此 sql 更改数据库的字符集和排序规则(首先备份): ALTER TABLE yourtable CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci
  • 能否请您在此处回显此命令。 show variables like 'character%';
  • AljoshaBre character_set_client utf8 character_set_connection utf8 character_set_database latin1 character_set_filesystem binary character_set_results utf8 character_set_server latin1 character_set_system utf8 character_sets_dir /usr/share/mysql/charsets/
  • 您可能应该更改您的数据库字符集。 use YOURDB;alter database YOURDB default charset UTF8;

标签: php str-replace


【解决方案1】:

也许数据库使用与您的 PHP 文件不同的编码。首先比较那些用bin2hex()函数(在PHP中)转换的字符串。

【讨论】:

    【解决方案2】:

    第二次尝试:

    PHP 文档的 cmets 中有很多建议。试试这些:

    1. http://www.php.net/manual/es/function.str-replace.php#106653
    2. http://www.php.net/manual/es/function.str-replace.php#75566
    3. http://www.php.net/manual/es/function.str-replace.php#72344

    尝试明确设置页面的字符类型。尝试将其放在标题中:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    

    或者,如果您使用的是 HTML 5:

    <meta charset="utf-8">
    

    【讨论】:

      【解决方案3】:

      我认为,由于您有一些奇怪的字符,它们可能超出 ascii 范围,您可能需要使用多字节字符串函数,尽管它没有 str_replace 模拟,您可能需要使用多字节正则表达式。

      【讨论】:

      • 是奇怪的迹象使它无法正常工作。所以我把它们改成了另一组字符。谢谢
      【解决方案4】:

      请看看这个,它会告诉你如何在网络应用程序中处理 UTF 字符

      UTF-8 in Web Apps

      【讨论】:

        猜你喜欢
        • 2013-08-14
        • 2015-01-23
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多