php按字数截取替换的方法:1、使用“function substr_format(){...}”方法进行截取替换;2、使用“function cut_string($str, $len){...}”方法进行截取替换。

本文操作环境:Windows7系统、PHP7.1版本、Dell G3电脑
php怎么按字数截取替换?
PHP截取指定长度的字符串,超出部分用 ..替换
function substr_format($text, $length, $replace='..', $encoding='UTF-8')
{
if ($text && mb_strlen($text, $encoding)>$length)
{
return mb_substr($text, 0, $length, $encoding).$replace;
}
return $text;
}还有
立即学习“PHP免费学习笔记(深入)”;
function cut_string($str, $len)
{
// 检查长度
if (mb_strwidth($str, 'UTF-8')<=$len)
{
return $str;
}
// 截取
$i = 0;
$tlen = 0;
$tstr = '';
while ($tlen < $len)
{
$chr = mb_substr($str, $i, 1, 'UTF-8');
$chrLen = ord($chr) > 127 ? 2 : 1;
if ($tlen + $chrLen > $len) break;
$tstr .= $chr;
$tlen += $chrLen;
$i ++;
}
if ($tstr != $str)
{
$tstr .= '...';
}
return $tstr;
}推荐:《PHP视频教程》
以上就是php怎么按字数截取替换的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号