2011-09-12 143 views
2

我得到的数据是这样的:“ӘІҢҒҮКҚӨҺ”。 将此数据转换为此:d398d086d2a2d292d2aed2b0d29ad3a8d2ba 然后为* .rtf格式添加“\'”:\'d3 \'8d \ '86 \'2a \'d2 \'2d \'ae \'2b \'d2 \广告\ 'A8 \' 2Bstr_replace给出错误结果

,然后我得somethingl IKE在此:\ 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("ӘІҢҒҮҰҚӨҺ"); 
?> 
+1

检查http://stackoverflow.com/questions/1451144/php-multi-byte-str-replace – thwd

+0

@汤姆,没有。这不适合我,这些信件是从MySQL数据库中获取的。他们在unicode(utf8)中。所以我试图比较hexed值并用rtf spec格式替换它。 –

+1

mb_str_replace是你在找什么 – ajreal

回答

0

由于“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=''; 
    } 

} 

在旧版本(的问题),这件事情被跳过主字符串的每个字符三分之一。所以现在它工作正常。

0

我看不出有什么直接的问题与您的代码,比你为榜样使用字符串包含任何在$input_arr序列的事实等。我手动添加\'d3\'8d到该列表,并且替换工作正常,所以这可能是您的问题的来源。

您出现的UTF-8被转换为逃逸Unicode字符作为\u{code}\'3f的ASCII码表示,所以你可能能够利用the utf8tohtml function described in this comment,其转义字符在&#{code};格式。

+0

我已经发现我的错误并解决了问题。 :)哦,并感谢utf8tohtml。 –