Home >Backend Development >PHP Tutorial >php intercept function containing mixed string lengths

php intercept function containing mixed string lengths

WBOY
WBOYOriginal
2016-07-25 08:44:221087browse
  1. It must be possible for Chinese, English and special characters.
  2. //utf-8 Chinese interception, single-byte interception mode
  3. function cn_substr_utf8($str,$length,$append='...',$start=0){
  4. if(strlen($str)<$ start+1){
  5. return '';
  6. }
  7. preg_match_all("/./su",$str,$ar);
  8. $str2='';
  9. $tstr='';
  10. for($i=0 ;isset($ar[0][$i]);$i++){
  11. if(strlen($tstr)<$start){
  12. $tstr.=$ar[0][$i];
  13. }else {
  14. if(strlen($str2)<$length + strlen($ar[0][$i])){
  15. $str2.=$ar[0][$i];
  16. }else{
  17. break;
  18. }
  19. }
  20. }
  21. return $str==$str2?$str2:$str2.$append;
  22. }
  23. //----Usage examples are as follows:
  24. echo cn_substr_utf8('I am a, and ha, oh Also,,country!',12);
Copy code

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