Home > Backend Development > PHP Tutorial > Function for utf8 encoded string interception

Function for utf8 encoded string interception

WBOY
Release: 2016-07-25 09:07:12
Original
918 people have browsed it
  1. /*

  2. * 用于utf8编码的字符串截取
  3. */
  4. function utf8_substr($str,$position,$length){
  5. $start_position = strlen($str);
  6. $start_byte = 0;
  7. $end_position = strlen($str);
  8. $count = 0;
  9. for($i = 0; $i < strlen($str); $i++){
  10. if($count >= $position && $start_position > $i){
  11. $start_position = $i;
  12. $start_byte = $count;
  13. }
  14. if(($count-$start_byte)>=$length) {
  15. $end_position = $i;
  16. break;
  17. }
  18. $value = ord($str[$i]);
  19. if($value > 127){
  20. $count++;
  21. if($value >= 192 && $value <= 223) $i++;
  22. elseif($value >= 224 && $value <= 239) $i = $i + 2;
  23. elseif($value >= 240 && $value <= 247) $i = $i + 3;
  24. else die('Not a UTF-8 compatible string');
  25. }
  26. $count++;

  27. }

  28. return(substr($str,$start_position,$end_position-$start_position));
  29. }
  30. ?>

复制代码


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