在項目中,遇到一個需求,如我要截取一串字符串,而又不想截取半截的單詞,看了下php手冊的這個mb_strimwidth() 函數(shù),據(jù)說是不會打斷單詞的,可是測試沒有成功,于是乎自己寫個先,雖然有些小問題,但是勉強能用了,有時間再封裝的好點. 該函數(shù)的實現(xiàn)原理是利用wordwrap()打斷單詞,然后用mb_strlen()計算單詞的長度,截取到需要被截取的長度即可. 如下測試:
//原字符串
$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,100);
//結(jié)果:
readonly this boolean attribute indicates that the user cannot modify value of control. Unlike disabled attribute, …
/**
* 該函數(shù)截取英文字符串,不會打斷英文單詞,就是說不會把一個單詞截取一半
* note: 不適用于中文,當(dāng)然改改也可以
* note: 目前該函數(shù)有點小bug,$cutlength 不是指長度,而是計算所有單詞的長度到了這個數(shù)時停止,其實也就是空格的長度被忽略了
*/
function wordcut($string, $cutlength = 250, $replace = ‘…’){
//長度不足直接返回
if(mb_strlen($string) <= $cutlength){
return $string;
}else{
//計算當(dāng)前單詞總長度
$totalLength = 0;
$datas = $newwords = array();
//打亂文本
$wrap = wordwrap($string,1,"t");
//組成數(shù)組
$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;
}
}
更多信息請查看IT技術(shù)專欄