2010-08-27 48 views
4

我遇到了PHP(5.2)無法在字符串中找到字符''的問題,雖然它顯然存在。PHP和字符編碼問題Â字符

我意識到底層問題與字符編碼有關,但不幸的是我無法控制源內容。我收到它作爲UTF-8,這些字符已經在字符串中。

我只是想從字符串中刪除它。 strpos(),str_replace(),preg_replace(),trim()等無法正確識別它。

我的字符串是這樣的:前

"� � � A lot of couples throughout the World" 

我甚至嘗試函數utf8_encode()和utf8_decode():

"Â Â Â A lot of couples throughout the World " 

如果我這樣做:

$string = str_replace('Â','',$string); 

我得到這個str_replace,沒有運氣。

解決方案是什麼?我已經拋出所有我能找到它......

+0

爲£:$輸入= str_replace函數( 「£」, 「£」,$輸入); – atwellpub 2010-12-15 05:23:02

回答

3

我用這個:

function replaceSpecial($str){ 
$chunked = str_split($str,1); 
$str = ""; 
foreach($chunked as $chunk){ 
    $num = ord($chunk); 
    // Remove non-ascii & non html characters 
    if ($num >= 32 && $num <= 123){ 
      $str.=$chunk; 
    } 
} 
return $str; 
} 
+0

您可以將其擴展爲允許所有ASCII字符通過將32更改爲0和123更改爲255。 – KeatsKelleher 2010-08-27 19:16:42

+0

這將刪除許多字符,而不僅僅是重音。 – shamittomar 2010-08-27 19:17:52

+0

對,所有不漂亮,非ASCII字符 – KeatsKelleher 2010-08-27 19:20:18

4
$string = str_replace('Â','',$string); 

這個「Â」是如何編碼的?如果腳本文件保存爲iso-8859-1,則字符串'Â'被編碼爲一個字節序列xC2,而(/ one)utf-8表示爲xC3 x82。 php的str_replace()在字節級別上工作,即它只「知道」單字節字符。

看到http://docs.php.net/intro.mbstring

+0

+1,因此可以將替換寫爲:'str_replace(chr(195).chr(130),'',$ string)'...(其中'195'和'130'爲'xC3'和'或者,因爲PHP支持十六進制數字:'str_replace(chr(0xC3),chr(0x82),'',$ string)'...... – ircmaxell 2010-08-27 19:39:07

+0

我還發現mb_ereg_replace()似乎不能正常工作;這不是它的目的嗎?您的信息非常有用,我一定會閱讀您鏈接的文檔。謝謝! – Travis 2010-08-27 20:10:25

+0

@Travis:您傳遞給mbstring函數的參數也必須正確編碼。如果您的腳本中有字符串文字(如''),那麼編碼取決於您如何保存腳本文件。 – VolkerK 2010-08-27 23:37:13