php按字符无乱码截取中文的方法_PHP教程

WBOY
Release: 2016-07-13 10:00:00
Original
1065 people have browsed it

php按字符无乱码截取中文的方法

 这篇文章主要介绍了php按字符无乱码截取中文的方法,涉及php操作中英文字符串的技巧,非常具有实用价值,需要的朋友可以参考下

 

 

本文实例讲述了php按字符无乱码截取中文的方法。分享给大家供大家参考。具体实现方法如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

//$str 待截取的字符串

//$len 截取的字符个数

//$chars 已经截取的字符数

//$res 保存的字符串

//$chars 保存已经截取的字符串个数

//$offset 截取的偏移量

//$length 字符串的字节数

//若$len>$str的字符个数,造成无谓的while循环,($offset

function utf8sub($str,$len){

if($len

return ;

}

$res="";

$offset=0;

$chars=0;

$length=strlen($str);

while($chars

$hign=decbin(ord(substr($str,$offset,1)));

if(strlen($hign)

$count=1;

}elseif(substr($hign,0,3)=="110"){

$count=2;

}elseif(substr($hign,0,4)=="1110"){

$count=3;

}elseif(substr($hign,0,5)=="11110"){

$count=4;

}elseif(substr($hign,0,6)=="111110"){

$count=5;

}elseif(substr($hign,0,7)=="1111110"){

$count=6;

}

$res.=substr($str,$offset,$count);

$offset+=$count;

$chars+=1;

}

return $res;

}

function utf8sub1($str,$len){

$chars=0;

$res="";

$offset=0;

$length=strlen($str);

while($chars

$hign=decbin(ord(substr($str,$offset,1)));

if(strlen($hign)

$count=1;

}elseif($hign & "11100000"=="11000000"){

$count=2;

}elseif($hign & "11110000"=="11100000"){

$count=3;

}elseif($hign & "11111000"=="11110000"){

$count=4;

}elseif($hign & "11111100"=="11111000"){

$count=5;

}elseif($hign & "11111110"=="11111100"){

$count=6;

}

$res.=substr($str,$offset,$count);

$chars++;

$offset+=$count;

}

return $res;

}

$a="中华ah人民hdj";

echo utf8sub($a,5);

?>

希望本文所述对大家的php程序设计有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/975121.htmlTechArticlephp按字符无乱码截取中文的方法 这篇文章主要介绍了php按字符无乱码截取中文的方法,涉及php操作中英文字符串的技巧,非常具有实用价值...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!