Home > Backend Development > PHP Tutorial > Example of php custom function to intercept the length of Chinese characters

Example of php custom function to intercept the length of Chinese characters

WBOY
Release: 2016-07-25 08:53:21
Original
798 people have browsed it
  1. function msubstr($str,$start,$len) {
  2. $strlen=$start+$len;
  3. for($i=0;$i<$strlen;$i++) {
  4. if(ord( substr($str,$i,1))>0xa0) {
  5. $tmpstr.=substr($str,$i,2);
  6. $i++;
  7. } else
  8. $tmpstr.=substr($str,$ i,1);
  9. }
  10. return $tmpstr;
  11. }
Copy code

Call:

  1. $str="This character is so long,^_^";

  2. $Short_Str=showShort($str,4);//Intercept the first 4 Chinese characters , the result is: this character...
  3. Echo "$Short_Str";
  4. Function csubstr($str,$start,$len)
  5. {
  6. $strlen=strlen($str);
  7. $clen=0;
  8. for( $i=0;$i<$strlen;$i++,$clen++)
  9. {
  10. if ($clen>=$start+$len)
  11. break;
  12. if(ord(substr($str,$i,1)) >0xa0)
  13. {
  14. if ($clen>=$start)
  15. $tmpstr.=substr($str,$i,2);
  16. $i++;
  17. } bbs.it-home.org
  18. else
  19. {
  20. if ($clen>=$start)
  21. $tmpstr.=substr($str,$i,1);
  22. }
  23. }

  24. return $tmpstr;

  25. }
  26. Function showShort($ str,$len)
  27. {
  28. $tempstr = csubstr($str,0,$len);
  29. if ($str<>$tempstr)
  30. $tempstr .= "..."; //What to end with , just modify it here.

  31. return $tempstr;

  32. }

Copy the code

Here we share a more concise method of intercepting the length of Chinese characters:

  1. $len = 19;
  2. $text = "How to display only the first few words of a long news title and replace it with...?";
  3. echo strlen ($text)<=$len ? $text : (substr($text,0,$len).chr(0)."....");
Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template