Home > Backend Development > PHP Tutorial > 如何分别全角和半角以避免乱码_PHP

如何分别全角和半角以避免乱码_PHP

WBOY
Release: 2016-06-01 12:42:30
Original
815 people have browsed it

function ChgTitle($title)
{

$length = 46;
if (strlen($title)>$length) {
$temp = 0;
for($i=0; $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