簡體   English   中英

如何替換字符串中的亂碼?

[英]How to replace garbled characters in a string?

我有這個文字...

“我並不想變得可信,”戴維笑着承認道。

...並且我想刪除那些有趣的字符,我嘗試過str_replace()但是它不起作用。

有任何想法嗎?

您可能已使用與源代碼不同的編碼來處理文本。

因此,如果文本為UTF-8,則當前不將其作為UTF-8處理。 最簡單的方法是發送標題,例如...

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

您也可以添加meta元素,但確保它是head元素的第一個子元素。

您需要從源頭上解決此問題,而不是稍后嘗試對其進行修補(永遠無法正常工作)。

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

不同的來源通常具有不同的編碼,因此您需要指定呈現視圖的編碼。 Utf-8最受歡迎,因為它涵蓋了所有ASCII和許多其他語言。

php的utf8_(de)encode將iso-8859-1轉換為utf-8,相反的和常規的字符串操作函數不是多字節的(utf-8可以識別)字符。 您可以使用特定於mb_strings的函數,也可以使用某些參數啟用編碼。

//如果我誤會了

好吧,您正在使用可能應該使用的其他字符編碼(您應該使用utf-8編碼),所以我將對其進行更改,而不是嘗試使用快速修復方法立即修復它(您會遇到這樣總體上減少了問題)。


如果您真的想使用PHP進行修復,則可以使用ctype_alpha()函數。 您應該能夠執行以下操作:

$theString = "your text here"; // your input string

$newString = ""; // your new string
$i = 0;
while($theString[$i]) // while there are still characters in the string
{
    if(ctype_alpha($theString[$i]) // if it's a character in your current set
    { 
       $newString .= $theString[$i]; // add it to the new string, increment pointer, and go to next loop iteration
       $i++;
       continue; 
    } // if the specific character at the $i index is an alphabetical character, add it to the new string
    else
    {
       $i++;
    } // if it's a bad character, just move the pointer up by one for the next iteration
}

然后根據需要使用$ newString。 確實,只是更改您的字符編碼,而不要這樣做。 您希望整個項目中的編碼都相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM