漢字按字節截取亂碼

<?php

/**
*  實現原理:
*  1  對漢字按字節進行截取處理, 
*		若是檢查到無亂碼,說明截取合適
*       若是檢查到有亂碼,對字符串進行多字節截取, 
**/
$source_string = "中華人民共和國";
define("ALLOW_LENGTH",6);
define('ALLOW_LENGTH_ERROR',7);

$cut_string = substr($source_string,0,ALLOW_LENGTH);
echo $cut_string."&nbsp;&nbsp;";

$check_result = mb_check_encoding($cut_string,'UTF-8');

echo $check_result == true ?  'true' : 'false';
echo "&nbsp;&nbsp;正常截取漢字<br />";

$cut_string_error = substr($source_string,0,ALLOW_LENGTH_ERROR);
echo $cut_string_error."&nbsp;&nbsp;";

$check_result_error = mb_check_encoding($cut_string_error,'UTF-8');

echo $check_result_error == true ? 'true'  : 'false'; 
echo "&nbsp;&nbsp;截取漢字異常<br />";


$crc_cut_string_error = mb_substr($cut_string_error,0,-1,'utf-8');
echo $crc_cut_string_error."&nbsp;&nbsp;";
$check_result_error = mb_check_encoding($cut_string_error,'UTF-8');
echo $check_result_error == true  ? 'true' : 'false';
echo "&nbsp;&nbsp;修正截取結果<br />";

?>
相關文章
相關標籤/搜索