php 不同编码下的字符串长度区分_PHP

WBOY
Release: 2016-06-01 12:22:45
Original
1363 people have browsed it
UTF-8的中文字符串是三个字节
复制代码 代码如下:
//编码UTF-8
echo strlen('测试文字a测试文字');
echo '-';
echo mb_strlen('测试文字a测试文字','utf-8');
?>
输出:25-9

GB2312的中文字符串是二个字节
复制代码 代码如下:
//编码GB2312
echo strlen('测试文字a测试文字');
echo '-';
echo mb_strlen('测试文字a测试文字','Gb2312');
?>

输出:17-9
在Mysql数据库(5.1以后的版本)中,如果字段类型为varchar(10)则可插入10个字符(不是字节);
所以在判断字符串的长度时需要根据文档编码来区分。
符一个简单的UTF-8下字符串截取(按字符个数截取)
复制代码 代码如下:

/*
* UTF-8字符串截取
* $str 要截取的字串
* $start 截取起始位置
* $length 截取长度
*/
function cutStr($str,$start,$length) {
$restr = '';
$j = 0;
$end = $length + $start - 1;
$plen = strlen($str);
for($i=0;$i$restr .= ord($str[$i])>127 ? $str[$i].$str[++$i].$str[++$i] : $str[$i];
$j++;
if ($j if ($j >= $end){break;}
}
$restr .='';
return $restr;
}
$str = '中新网9月24日电 二十国集团(G20)领导人第三次金融峰会今日将在美国匹兹堡召开。';
echo $str;
echo '
';
echo utf8_substr($str,0,25);
echo '
';
?>
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!