9999热视频三级毛片AV区|日韩欧美精品狼友观看视频|av在线成人免费AA片|日韩三级AV电影|久久亚洲私人国产精品vA|亚洲无码卡一卡二卡三|手机在线免费看黄色片|婷婷尹人在线婷婷五月手机网|99爱在线播放|欧美成人色情视频品

php截取字符串函數(shù)的方法
來源:易賢網(wǎng) 閱讀:1233 次 日期:2014-09-18 11:29:12
溫馨提示:易賢網(wǎng)小編為您整理了“php截取字符串函數(shù)的方法”,方便廣大網(wǎng)友查閱!

在項目中,遇到一個需求,如我要截取一串字符串,而又不想截取半截的單詞,看了下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: 不適用于中文,當然改改也可以

* note: 目前該函數(shù)有點小bug,$cutlength 不是指長度,而是計算所有單詞的長度到了這個數(shù)時停止,其實也就是空格的長度被忽略了

*/

function wordcut($string, $cutlength = 250, $replace = ‘…’){

//長度不足直接返回

if(mb_strlen($string) <= $cutlength){

return $string;

}else{

//計算當前單詞總長度

$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ù)專欄

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:php截取字符串函數(shù)的方法
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點

版權(quán)所有:易賢網(wǎng)