当前位置:Gxlcms > PHP教程 > php按照指定长度截取字符串的代码

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

时间:2021-07-01 10:21:17 帮助过:25人阅读

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

人气教程排行