如何在cakephp中截取中文字符串?

本來覺得 網站推廣要本身寫helper去截取中文字符串,沒想到cakephp的Text helper類中已經提供了truncate方法。下面是truncate方法的原型。

引用
truncate
    truncate(string $text, int $length=100, array $options)
    Cuts a string to the $length and adds a suffix with ‘ending’ if the text is longer than $length. If ‘exact’ is passed as false, the truncation will occur after the next word ending. If ‘html’ is passed as true, html tags will be respected and will not be cut off.


Text->truncate方法有3個參數:

  • $text:須要截取的字符串
  • $length:須要截取的長度,默認是截取100個字符
  • $options:數組參數。ending表示在截取後的字符串結尾加上ending字符串;exact若是是false的話則不會截斷word;html若是是true的話則不會截斷html tag

下面的代碼演示瞭如何使用tuncate方法:

Php代碼   收藏代碼
  1. echo $this->Text->truncate(  
  2.     'The killer crept forward and tripped on the rug.',  
  3.     22,  
  4.     array(  
  5.         'ending' => '...',  
  6.         'exact' => false  
  7.     )  
  8. );  


上面 網站推廣的代碼將輸出 The killer crept…
注意:若是是截取中文字符串的話exact最好置爲true,不然漢語字符將沒法被截斷 (fblww-0308)
相關文章
相關標籤/搜索