欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-04-12 15:13:56
...

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