Home >Backend Development >PHP Tutorial >中文乱码 - PHP 如何匹配文本中是否含有乱码字符

中文乱码 - PHP 如何匹配文本中是否含有乱码字符

WBOY
WBOYOriginal
2016-06-06 20:33:591216browse

网站经常有乱码用户名的提交,如何才可以通过PHP来判断文本中是否含有乱码?

<code>php</code><code>#UTF-8 
$str = '办证';
preg_match_all('/(...)/',$str,$matches);
print_r($matches);
die;
</code>
<code>Array
(
    [0] => Array
        (
            [0] => 办
            [1] => 
            [2] => 证
        )

    [1] => Array
        (
            [0] => 办
            [1] => 
            [2] => 证
        )

)

</code>

回复内容:

网站经常有乱码用户名的提交,如何才可以通过PHP来判断文本中是否含有乱码?

<code>php</code><code>#UTF-8 
$str = '办证';
preg_match_all('/(...)/',$str,$matches);
print_r($matches);
die;
</code>
<code>Array
(
    [0] => Array
        (
            [0] => 办
            [1] => 
            [2] => 证
        )

    [1] => Array
        (
            [0] => 办
            [1] => 
            [2] => 证
        )

)

</code>

这是你的前台和后台的编码不一致造成的,前台输入的时候就应该进行判断是否让用户输入非法字符。

以下补充内容:

<code>php</code><code><?php /*
仅适用于php文档为ANSI编码
*/

/* 关闭页面错误提示,iconv("","UTF-8","办证证")这段代码一旦转入不是UTF-8编码就会错误 */
error_reporting(0);

$str = "办证"; //接收来的字符串

//尝试转换编码,
$str = iconv('', 'UTF-8', $str);

//匹配是否为UTF-8编码
function is_utf8($utf8str)
{
if (preg_match('/^([' . chr(228) . '-' . chr(233) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}){1}/', $utf8str) == true || preg_match('/([' . chr(228) . '-' . chr(233) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}){1}$/', $utf8str) == true || preg_match('/([' . chr(228) . '-' . chr(233) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}){2,}/', $utf8str) == true) {
return true;
} else {
return false;
}
}

if (is_utf8($str) == 1) {
//由于文件是ANSI编码,此处需用UTF8转换,页面才能正常输出
echo iconv('GB2312', 'UTF-8', '匹配正确');
} else {
//同上
echo iconv('GB2312', 'UTF-8', '匹配错误');
}
?>
</code>

3个字的编码为\u529e\ue708\u8bc1,是utf-8,不知道有什么办法

一是前台输入的时候进行非法字符的判断和处理,这样可以避免输入性乱码;二是前台和后台的编码应该一致才会避免发生乱码的现象。

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