怎麼在cakephp中截取中文字串

來源:互聯網
上載者:User
如何在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方法:

echo $this->Text->truncate(    'The killer crept forward and tripped on the rug.',    22,    array(        'ending' => '...',        'exact' => false    ));


上面的代碼將輸出 The killer crept…
注意:如果是截取中文字串的話exact最好置為true,否則漢語字元將無法被截斷
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.