php截取字串函數的方法

來源:互聯網
上載者:User

  在項目中,遇到一個需求,如我要截取一串字串,而又不想截取半截的單詞,看了下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;

  }

  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.