首頁 >後端開發 >php教程 >php依照指定長度截取字串的程式碼

php依照指定長度截取字串的程式碼

WBOY
WBOY原創
2016-07-25 08:44:251652瀏覽

php按照指定长度截取字符串的代码,如果字符串超出了指定的长度,会用...替换,不过这段代码不支持中英文的区分

  1. //if a string is longer than the defined length,
  2. //it will add 3 periods to the end of the string.
  3. //you can change it to what ever you want for example:
  4. //return substr($str,0,$len).'[Read More]';
  5. //http://www.sharejs.com
  6. function strLength($str,$len){
  7. $lenght = strlen($str);
  8. if($lenght > $len){
  9. return substr($str,0,$len).'...';
  10. }else{
  11. return $str;
  12. }
  13. }
  14. $str = "This is a fairly long string.";
  15. //The fist part is the string, the second part is how long it can be
  16. echo strLength($str,10).'
    ';
  17. echo strLength($str,30);
  18. ?>
复制代码

php


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn