首页  >  文章  >  后端开发  >  php按照指定长度截取字符串的代码

php按照指定长度截取字符串的代码

WBOY
WBOY原创
2016-07-25 08:44:251628浏览

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