Home > Backend Development > PHP Tutorial > PHP chr() ord() Chinese interception garbled code problem solution_PHP tutorial

PHP chr() ord() Chinese interception garbled code problem solution_PHP tutorial

WBOY
Release: 2016-07-21 15:50:20
Original
1572 people have browsed it

Copy code The code is as follows:

$lenth = 19;
$str = "How to A long news title only displays the first few words and replaces it with...? ";
echo strlen($str)<=$lenth ? $str : (substr($str,0, $lenth).chr(0)."....");
?>

Copy code Code As follows:

/*
@ Another method, use the ord() function:
@ Applicable to gb2312 encoding:
*/
$str = "How to display only the first few words of a long news title and replace it with...?";
function gb2312_substr($str, $limit) {
$restr = '';
for($i=0;$i< $limit-3;$i++) {
$restr .= ord($str[$i])>127 ? $str[$i ].$str[++$i] : $str[$i];
}
return $restr;
}
/*
@ The following only applies to utf-8 encoding ;
*/
function utf8_substr($str, $limit) {
$restr = '';
for($i=0;$i< $limit-3;$i++) {
$restr .= ord($str[$i])>127 ? $str[$i].$str[++$i].$str[++$i] : $str[$i ];
}
return $restr;
}
//Explain the first one above: chr(0) is not null, null means nothing, and the value of chr(0) is 0. Expressed as hexadecimal, it is 0x00, and expressed as binary, it is 00000000. Although chr(0) will not display anything, it is a character. Although chr(0) does not display anything, it is a character. When a Chinese character is truncated, according to the encoding rules, he always has to pull the other characters behind as Chinese characters for interpretation. This is the reason why garbled characters appear.
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/319409.htmlTechArticleCopy the code as follows: ?php $lenth = 19; $str = "How to add a long title to the news Only display the first few words and replace them with...? "; echo strlen($str)=$lenth ? $str : (sub...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template