php截取字符串函數(shù)的方法
來源:易賢網(wǎng) 閱讀:819 次 日期: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: 不適用于中文,當(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ù)專欄

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機網(wǎng)站地址:php截取字符串函數(shù)的方法
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報警專用圖標(biāo)