Home  >  Article  >  Backend Development  >  php按照指定长度截取字符串的代码

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

WBOY
WBOYOriginal
2016-07-25 08:44:251503browse

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn