Home >Backend Development >PHP Tutorial >PHP method to determine whether a string encoding is utf8 and convert it_PHP tutorial

PHP method to determine whether a string encoding is utf8 and convert it_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:53:55914browse

Regarding the problem of garbled strings under PHP, when there are two encodings on a page, garbled characters will appear no matter which encoding you choose. So how can we solve this problem? The method provided by the editor of Liehuo:

1. First, according to international practice, check whether your file encoding is consistent with the database and page encoding.

Two. If there is no problem with "one", then you need to determine the encoding of the string first. We only need to determine one type. Regarding the issue of detecting whether it is utf8 encoding, Bangkejia has published related articles before, but it is not very good. Use it. I found a relatively perfect function on the Internet today. The code is as follows:

Copy to ClipboardLiehuo.Net CodesQuoted content: [www.bkjia.com] function is_utf8($liehuo_net)
{
if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128) ."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$liehuo_net) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1 }[".chr(128)."-".chr(191)."]{1}){1}$/",$liehuo_net) == true || preg_match("/([".chr(228 )."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-". chr(191)."]{1}){2,}/",$liehuo_net) == true)
{
return true;
}
else
{
return false;
}

}

Now let’s talk about how to use it. Experts don’t need to read it, because some beginners don’t know how to introduce and use this function. The following is the method.

1. Save the above code as a separate file, for example: liehuo_func_validt.php, save it to the root directory of the website, then import it into the file and add the following code:

Copy to ClipboardLiehuo.Net CodesQuoted content: [www.bkjia.com] require( "liehuo_func_validt.php" );

Next, judge the code and write it below the above code:

Copy to ClipboardLiehuo.Net CodesQuoted content: [www.bkjia.com] if(is_utf8($liehuo)==1)
{
$liehuo = iconv("utf-8","gbk",$liehuo);
}

That’s it.

Two. Put the judgment function directly at the top of the file, and then add the judgment code, which is more verbose, haha. Pay more attention to Bangke Home and support Liehuo.Net.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364702.htmlTechArticle Regarding the problem of garbled strings under PHP, when there are two encodings on a page, no matter which one you choose Garbled characters will appear, so how can we solve this problem? Editor Agni gives...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn