php截取字符串

1.substr(源字符串,其实位置[,长度])-截取字符串返回部分字符串

 

  1. <?php
  2. $str ="phpddt.com";
  3. echo substr($str,2);//pddt.com
  4. echo substr($str,2,3);//pdd
  5. echo substr($str,-2);//om 负数从结尾开始取
  6. ?>

 

但是当你截取中文字符串的时候很容易出现乱码,因为一个汉字是两个字节,而一个英文字母是一个字节。解决办法如下:

2.mb_substr(),使用方法和substr相同,不过要开启php.ini里面extension=php_mbstring.dll扩展,不用担心,一般的空间商

都会开启这个扩展的。

 

  1. <?php
  2. echo mb_substr("php点点通",1,3,"UTF-8");//hp点
  3. ?>

 

网上也有很多中文字符串截取教程,实现起来比较复杂,感觉还是用php自带的函数实现起来比较好。整理的网络资料(php代码)如下:

(1)截取GB2312中文字符串

 

  1. <?php
  2. //截取GB2312中文字符串
  3. function mysubstr($str, $start, $len){
  4. $tmpstr ="";
  5. $strlen = $start + $len;
  6. for($i =0; $i < $strlen; $i++){
  7. if(ord(substr($str, $i,1))>0xa0){
  8. $tmpstr .= substr($str, $i,2);
  9. $i++;
  10. }else
  11. $tmpstr .= substr($str, $i,1);
  12. }
  13. return $tmpstr;
  14. }
  15. echo mysubstr("php点点通",1,5);//php点
  16. ?>

 

(2)截取utf8编码的多字节字符串 

 

  1. <?php
  2. //截取utf8字符串
  3. function utf8Substr($str, $from, $len)
  4. {
  5. return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
  6. '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
  7. '$1',$str);
  8. }
  9. echo utf8Substr("php点点通",1,5);//hp点点通
  10. ?>

 

(3)支持 utf-8、gb2312都支持的汉字截取函数 

 

  1. <?php
  2. //同时支持 utf-8、gb2312都支持的汉字截取函数 ,默认编码是utf-8
  3. function cut_str($string, $sublen, $start =0, $code ='UTF-8')
  4. {
  5. if($code =='UTF-8')
  6. {
  7. $pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
  8. preg_match_all($pa, $string, $t_string);if(count($t_string[0])- $start > $sublen)return join('', array_slice($t_string[0], $start, $sublen))."...";
  9. return join('', array_slice($t_string[0], $start, $sublen));
  10. }
  11. else
  12. {
  13. $start = $start*2;
  14. $sublen = $sublen*2;
  15. $strlen = strlen($string);
  16. $tmpstr ='';for($i=0; $i<$strlen; $i++)
  17. {
  18. if($i>=$start && $i<($start+$sublen))
  19. {
  20. if(ord(substr($string, $i,1))>129)
  21. {
  22. $tmpstr.= substr($string, $i,2);
  23. }
  24. else
  25. {
  26. $tmpstr.= substr($string, $i,1);
  27. }
  28. }
  29. if(ord(substr($string, $i,1))>129) $i++;
  30. }
  31. if(strlen($tmpstr)<$strlen ) $tmpstr.="...";
  32. return $tmpstr;
  33. }
  34. }
  35. $str ="php点点通提供原创php教程";
  36. echo cut_str($str,8,0);//php点点通提供...
  37. ?>

 

转自:http://www.phpddt.com/php/366.html

参考:http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2009/0114/313.html

posted @ 2013-11-06 16:36  losesea  阅读(5166)  评论(0编辑  收藏  举报