在項(xiàng)目中,遇到一個(gè)需求,如我要截取一串字符串,而又不想截取半截的單詞,看了下php手冊(cè)的這個(gè)mb_strimwidth() 函數(shù),據(jù)說是不會(huì)打斷單詞的,可是測(cè)試沒有成功,于是乎自己寫個(gè)先,雖然有些小問題,但是勉強(qiáng)能用了,有時(shí)間再封裝的好點(diǎn). 該函數(shù)的實(shí)現(xiàn)原理是利用wordwrap()打斷單詞,然后用mb_strlen()計(jì)算單詞的長(zhǎng)度,截取到需要被截取的長(zhǎng)度即可. 如下測(cè)試:
//原字符串
$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ù)截取英文字符串,不會(huì)打斷英文單詞,就是說不會(huì)把一個(gè)單詞截取一半
* note: 不適用于中文,當(dāng)然改改也可以
* note: 目前該函數(shù)有點(diǎn)小bug,$cutlength 不是指長(zhǎng)度,而是計(jì)算所有單詞的長(zhǎng)度到了這個(gè)數(shù)時(shí)停止,其實(shí)也就是空格的長(zhǎng)度被忽略了
*/
function wordcut($string, $cutlength = 250, $replace = ‘…’){
//長(zhǎng)度不足直接返回
if(mb_strlen($string) <= $cutlength){
return $string;
}else{
//計(jì)算當(dāng)前單詞總長(zhǎng)度
$totalLength = 0;
$datas = $newwords = array();
//打亂文本
$wrap = wordwrap($string,1,"t");
//組成數(shù)組
$wraps = explode("t",$wrap);
foreach ($wraps as $tmp){
//計(jì)算每個(gè)單詞的長(zhǎng)度
$datas[$tmp] = mb_strlen($tmp);
}
foreach ($datas as $word => $length){
//保存單詞的總長(zhǎng)度
$totalLength += $length;
//如果小于截取的長(zhǎng)度則保存
if($totalLength < $cutlength){
array_push($newwords,$word);
}else{
break;
}
}
//生成新字符串
$str = trim(implode(” “,$newwords));
return empty($str) ? $str : $str.’ ‘.$replace;
}
}
更多信息請(qǐng)查看IT技術(shù)專欄