php截取标题,PHP中文截取,文章标题(title)内容长度控制方法

这个是51js上面的文章,替换dedecms的 cn_substr 听说速度更快 ,不过代码 已经通过我自己的测试

$cfg_soft_lang ='utf-8';

/**

* 中英文截取字符串,汉字安2个字节

*

* @access public

* @param string $str 需要截取的字符串

* @param int $cutLen 截取的长度

* @param bool $cutSlashes 是否去掉\

* @param bool $addSlashes 是加\

* @param string $oDot 截取后加的字符串,如经常用的三个点

* @param bool $hasHtml 是否有html

* @return string

*/

function cn_substr($str, $cutLen, $oDot = null, $hasHtml = false, $cutSlashes = false, $addSlashes = false)

{

global $cfg_soft_lang;

$str = trim($str);

if ($cutSlashes) $str = stripslashes($str);

if ($hasHtml) {

$str = preg_replace('/(\|\r|\n|\s|\[.+?\])/is','', $str);

$str = htmlspecialchars($str);

} else {

$str = htmlspecialchars($str);

}

if ($cutLen && strlen($str) > $cutLen) {

$nStr ='';

if ($cfg_soft_lang =='utf-8'){

$n = 0;

$tn = 0;

$noc = 0;

while ($n < strlen($str)) {

$t = ord($str [$n]);

if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {

$tn = 1;

$n++;

$noc++;

} elseif (194 <= $t && $t <= 223) {

$tn = 2;

$n += 2;

$noc += 2;

} elseif (224 <= $t && $t < 239) {

$tn = 3;

$n += 3;

$noc += 2;

} elseif (240 <= $t && $t <= 247) {

$tn = 4;

$n += 4;

$noc += 2;

} elseif (248 <= $t && $t <= 251) {

$tn = 5;

$n += 5;

$noc += 2;

} elseif ($t == 252 || $t == 253) {

$tn = 6;

$n += 6;

$noc += 2;

} else {

$n++;

}

if ($noc >= $cutLen) break;

}

if ($noc > $cutLen) $n -= $tn;

$nStr = substr($str, 0, $n);

}else{

for ($i = 0; $i < $cutLen - 1; $i++) {

if (ord($str [$i]) > 127) {

$nStr .= $str [$i] . $str [$i + 1];

$i++;

} else {

$nStr .= $str [$i];

}

}

}

$str = $nStr . $oDot;

}

if ($addSlashes) $str = addslashes($str);

$str = htmlspecialchars_decode($str);

return trim($str);

}

ecshop 的cn_substr

/**

* 截取UTF-8编码下字符串的函数

*

* @param string $str 被截取的字符串

* @param int $length 截取的长度

* @param bool $append 是否附加省略号

*

* @return string

*/

function sub_str($str, $length = 0, $append = true)

{

$str = trim($str);

$strlength = strlen($str);

if ($length == 0 || $length >= $strlength)

{

return $str;

}

elseif ($length < 0)

{

$length = $strlength + $length;

if ($length < 0)

{

$length = $strlength;

}

}

if (function_exists('mb_substr'))

{

$newstr = mb_substr($str, 0, $length, EC_CHARSET);

}

elseif (function_exists('iconv_substr'))

{

$newstr = iconv_substr($str, 0, $length, EC_CHARSET);

}

else

{

//$newstr = trim_right(substr($str, 0, $length));

$newstr = substr($str, 0, $length);

}

if ($append && $str != $newstr)

{

$newstr .= '...';

}

return $newstr;

}

内容来源:https://blog.csdn.net/zhangfeng1133/article/details/47757239

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值