码迷,mamicode.com
首页 > Web开发 > 详细

php截取字符串时保持英文单词完整性的函数

时间:2016-03-08 23:12:43      阅读:393      评论:0      收藏:0      [点我收藏+]

标签:

/** 
* 该函数截取英文字符串,不会打断英文单词,就是说不会把一个单词截取一半 
* note: 不适用于中文,当然改改也可以 
* note: 目前该函数有点小bug,$cutlength 不是指长度,而是计算所有单词的长度到了这个数时停止,其实也就是空格的长度被忽略了 
*/ 
function wordcut($string, $cutlength = 250, $replace = ‘…‘){ 
//长度不足直接返回 
if(mb_strlen($string) <= $cutlength){ 
return $string; 
}else{ 
//计算当前单词总长度 
$totalLength = 0; 
$datas = $newwords = array(); 
//打乱文本 
$wrap = wordwrap($string,1,"\t"); 
//组成数组 
$wraps = explode("\t",$wrap); 

foreach ($wraps as $tmp){ 
//计算每个单词的长度 
$datas[$tmp] = mb_strlen($tmp); 
} 
foreach ($datas as $word => $length){ 
//保存单词的总长度 
$totalLength += $length; 
//如果小于截取的长度则保存 
if($totalLength < $cutlength){ 
array_push($newwords,$word); 
}else{ 
break; 
} 
} 
//生成新字符串 
$str = trim(implode(" ",$newwords)); 
return empty($str) ? $str : $str.‘‘.$replace; 
} 
}


$str = ‘readonly this boolean attribute indicates that the user cannot modify the value of the control. Unlike the disabled attribute, the readonly attribute does not prevent the user from clicking or selecting in the control. long ge blog\’s The value of a read-only control is still submitted with the form.‘; 

echo wordcut($str,105); 

 

php截取字符串时保持英文单词完整性的函数

标签:

原文地址:http://www.cnblogs.com/afeng2016/p/5255738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!