【问题标题】:str_replace gives wrong resultstr_replace 给出错误的结果
【发布时间】:2011-11-15 03:42:30
【问题描述】:

我得到这样的数据:“ӘІҢҒҮҰҚӨҺ”。 将此数据六边形:d398d086d2a2d292d2aed2b0d29ad3a8d2ba 然后为 *.rtf 格式添加“\”:\'d3\'8d\'86\'2a\'d2\'2d\'ae\'2b\'d2\'ad\'a8\'2b

然后我必须得到类似这样的东西:\u1179\'3f\u1240\'3f\u1186\'3f...

但 str_replace 只替换斜线 Q_Q。

有什么建议吗?

这里是完整的代码:

<?
function strToHex($string)
{
    $hex='';
    for ($i=0; $i < strlen($string); $i++)
    {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

function extra($txt) {
    $output_arr = array (
        //
        "\\u1179\\'3f","\\u1240\\'3f","\\u1186\\'3f","\\u1170\\'3f","\\u1198\\'3f","\\u1200\\'3f","\\u1178\\'3f","\\u1256\\'3f","\\u1210\\'3f"
    );

    $input_arr = array (
        // 
        "\\'d3\\'98","\\'d0\\'86","\\'d2\\'a2","\\'d2\\'92","\\'d2\\'ae","\\'d2\\'b0","\\'d2\\'9a","\\'d3\\'a8","\\'d2\\'ba"
    );

    echo "<br>";
    echo "data: ".$txt."<br>";
    $txt = strtohex($txt);
    echo "hex: ".$txt."<br>";
    for ($ii=0; $ii < strlen($txt); $ii++) {
        //
        if (strlen($tm1)<2) {
            //
            $tm1.=substr($txt,$ii,1);
        }
        else
            {
            //
            $ret.="\\'".$tm1;
            $tm1='';
        }

    }
    echo "RET:[".$ret."]<br>";
    $ret = str_replace($input_arr,$output_arr,$ret);
    echo "RETREP:[".$ret."]<br>";
    return $ret;
}

extra("ӘІҢҒҮҰҚӨҺ");
?>

【问题讨论】:

  • @Tom,不。这不适合我,这些字母取自 mysql db。他们在 unicode(utf8) 中。所以我正在尝试比较十六进制值并使用 rtf 规范格式替换它。
  • mb_str_replace 就是你要找的东西
  • 各位...字符串只包含字符[0-9a-f\\'],这种情况下多字节函数会实现什么?

标签: php unicode hex rtf str-replace


【解决方案1】:

由于“for”循环中的“if”逻辑,我得到了错误的结果。 这是正确的:

for ($ii=0; $ii < strlen($txt); $ii++) {
    //
    if (strlen($tm1)<2) {
        //
        $tm1.=substr($txt,$ii,1);
    }
    if (strlen($tm1)==2) {
        //
        $ret.="\\'".$tm1;
        $tm1='';
    }

}

在旧版本(问题)中,这件事是跳过主字符串的每三个字符。所以现在它可以正常工作了。

【讨论】:

    【解决方案2】:

    除了您用作示例的字符串不包含$input_arr 中的任何序列这一事实外,我认为您的代码没有直接问题。我手动将\'d3\'8d 添加到该列表中,并且替换工作正常,因此这可能是您的问题的根源。

    您似乎正在将 UTF-8 转换为将 Unicode 字符转义为 \u{code}\'3f 的 ASCII 表示,因此您可以利用 the utf8tohtml function described in this comment,它转义 &amp;#{code}; 格式的字符。

    【讨论】:

    • 我已经发现我的错误并解决了问题。 :) 哦,感谢 utf8tohtml。
    猜你喜欢
    • 2014-09-16
    • 2019-02-06
    • 2014-01-30
    • 2018-08-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多