Home > Backend Development > PHP Tutorial > 太长的标题要截断?如何分别全角和半角以避免乱码_PHP

太长的标题要截断?如何分别全角和半角以避免乱码_PHP

WBOY
Release: 2016-06-01 12:38:14
Original
1180 people have browsed it

作 者: lemann(lemann)

function ChgTitle($title)

{



$length
= 46;

if (strlen($title)>$length) {

$temp
= 0;

for($i=0; $i$length; $i++)

if (ord($title[$i]) > 128)

$temp
++;

if ($temp%2 == 0)

$title
= substr($title,0,$length)."...";

else

$title
= substr($title,0,$length+1)."...";

}

return $title;

}



原理就是截断一个字符
看看其ascII码是不是大于128如果是说明截断的是一个全角汉字那么就退后一个截断。用$length控制长度



备注
循环判断字符串里面的 >128

的字符个数
如果半角字符为偶数则表示位置刚好为整个汉字如果为奇数则为半个汉字需要取下一个字

Related labels:
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