


php iconv() : Detected an illegal character in input string_php技巧
May 17, 2016 am 09:22 AM開始是這樣用的
$str = iconv('UTF-8', 'GB2312', unescape(isset($_GET['str'])? $_GET['str']:''));
上線后報(bào)一堆這樣的錯(cuò):iconv() : Detected an illegal character in input string
考慮到GB2312字符集比較小,換個(gè)大的吧,于是改成GBK:
$str = iconv('UTF-8', 'GBK', unescape(isset($_GET['str'])? $_GET['str']:''));
上線后還是報(bào)同樣的錯(cuò)!
再認(rèn)真讀手冊(cè),發(fā)現(xiàn)有這么一段:
If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character.
于是改成:
$str = iconv('UTF-8', 'GBK//IGNORE', unescape(isset($_GET['str'])? $_GET['str']:''));
本地測(cè)試//IGNORE能忽略掉它不認(rèn)識(shí)的字接著往下轉(zhuǎn),并且不報(bào)錯(cuò),而//TRANSLIT是截掉它不認(rèn)識(shí)的字及其后面的內(nèi)容,并且報(bào)錯(cuò)。//IGNORE是我需要的。
現(xiàn)在等待上線看結(jié)果(這樣不是好的做法,繼續(xù)琢磨手冊(cè),上網(wǎng)搜搜看),呵呵。。。
在網(wǎng)上找到下面這篇文章,發(fā)現(xiàn)mb_convert_encoding也可以,但效率比iconv差。
轉(zhuǎn)換字符串編碼iconv與mb_convert_encoding的區(qū)別
iconv — Convert string to requested character encoding(PHP 4 >= 4.0.5, PHP 5)
mb_convert_encoding — Convert character encoding(PHP 4 >= 4.0.6, PHP 5)
用法:
string mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )
需要先啟用 mbstring 擴(kuò)展庫,在 php.ini里將; extension=php_mbstring.dll 前面的 ; 去掉
string iconv ( string in_charset, string out_charset, string str )
注意:
第二個(gè)參數(shù),除了可以指定要轉(zhuǎn)化到的編碼以外,還可以增加兩個(gè)后綴://TRANSLIT 和 //IGNORE,
其中:
//TRANSLIT 會(huì)自動(dòng)將不能直接轉(zhuǎn)化的字符變成一個(gè)或多個(gè)近似的字符,
//IGNORE 會(huì)忽略掉不能轉(zhuǎn)化的字符,而默認(rèn)效果是從第一個(gè)非法字符截?cái)唷?br>Returns the converted string or FALSE on failure.
使用:
1. 發(fā)現(xiàn)iconv在轉(zhuǎn)換字符"-"到gb2312時(shí)會(huì)出錯(cuò),如果沒有ignore參數(shù),所有該字符后面的字符串都無法被保存。不管怎么樣,這個(gè)"-"都無法轉(zhuǎn)換成功,無法輸出。另外mb_convert_encoding沒有這個(gè)bug.
2. mb_convert_encoding 可以指定多種輸入編碼,它會(huì)根據(jù)內(nèi)容自動(dòng)識(shí)別,但是執(zhí)行效率比iconv差太多;如:$str = mb_convert_encoding($str,"euc-jp","ASCII,JIS,EUC-JP,SJIS,UTF- 8");“ASCII,JIS,EUC-JP,SJIS,UTF-8”的順序不同效果也有差異
3. 一般情況下用 iconv,只有當(dāng)遇到無法確定原編碼是何種編碼,或者iconv轉(zhuǎn)化后無法正常顯示時(shí)才用mb_convert_encoding 函數(shù)
from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");
$str = mb_convert_encoding($str, "EUC-JP', "auto");
例子:
$content = iconv("GBK", "UTF-8", $content);
$content = mb_convert_encoding($content, "UTF-8", "GBK");

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
