萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php截取字符串函數的方法

php截取字符串函數的方法

  在項目中,遇到一個需求,如我要截取一串字符串,而又不想截取半截的單詞,看了下php手冊的這個mb_strimwidth() 函數,據說是不會打斷單詞的,可是測試沒有成功,於是乎自己寫個先,雖然有些小問題,但是勉強能用了,有時間再封裝的好點. 該函數的實現原理是利用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);

  //結果:

  readonly this boolean attribute indicates that the user cannot modify value of control. Unlike disabled attribute, …

  /**

  * 該函數截取英文字符串,不會打斷英文單詞,就是說不會把一個單詞截取一半

  * 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;

  }

  }

copyright © 萬盛學電腦網 all rights reserved