2011-01-25 148 views
24

我還不明白iconv是如何工作的。PHP:用iconv處理特殊字符

例如,

$string = "Löic & René"; 
$output = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $string); 

我得到的,

注意:的iconv()[function.iconv]: 在...

檢測到非法的字符輸入 串

$string = "Löic";$string = "René";

我得到的,

說明:iconv() [function.iconv]:檢測到輸入字符串不完整的多字節字符

我什麼也沒得到與$string = "&";

有兩套不同的輸出,我需要把它們存儲在兩個不同的我的數據庫的表內列,

  1. 我需要Löic & René轉換爲Loic & Rene清潔網址PU rposes。

  2. 我需要保持它們原樣 - Löic & René as Löic & René然後只在將它們顯示在我的html頁面上時將它們轉換爲htmlentities($string, ENT_QUOTES);

我試圖與一些在下面php.net的建議,但仍然不工作,

我有地方,我需要音譯一些字符的情況,而忽視了其他人(對怪異的變音符號象泉或hamza)。添加// TRANSLIT // IGNORE似乎爲我做了詭計。它能夠音譯所有可以音譯的東西,但是會拋出不可能的東西。

所以:

$string = "ʿABBĀSĀBĀD"; 

echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string); 
// output: [nothing, and you get a notice] 

echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string); 
// output: ABBSBD 

echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string); 
// output: ABBASABAD 
// Yay! That's what I wanted! 

和另一個

Andries Seutens 07-Nov-2009 07:38 
When doing transliteration, you have to make sure that your LC_COLLATE is properly set, otherwise the default POSIX will be used. 

To transform "rené" into "rene" we could use the following code snippet: 
setlocale(LC_CTYPE, 'nl_BE.utf8'); 

$string = 'rené'; 
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string); 

echo $string; // outputs rene 

我怎樣才能實際工作出來?

感謝。

編輯:

這是源文件,我測試的代碼,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" class="no-js"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head> 
<?php 
$string = "Löic & René"; 
$output = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $string); 
?> 
</html> 
+0

順便說一句:你知道`ö`&`é`在ISO-8859-1?除了不正確的輸入字符集之外,您可能希望將輸出字符集更改爲「ASCII // TRANSLIT」。 – Wrikken 2011-01-25 14:51:07

+7

我很困惑這些字符... – laukok 2011-01-25 15:09:50

+1

謝謝!我不得不將一些韓文字符解碼爲UTF-8,這真是頭疼 - 最終,唯一有幫助的是: `$ converted = iconv('EUC-KR','UTF-8 // TRANSLIT', $ data);` – ShayLivyatan 2016-07-04 09:23:56

回答

12

,做您保存源文件中的UTF-8編碼?如果沒有(並且我猜你以後不會產生「不完整的多字節字符」錯誤),那麼先嚐試一下。

18
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($s));