PHP编程

php截取字符串

日期:2015-06-28 00:00:00 来源: IT猫扑网

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

  1. php
  2. $str ="itmop.com";
  3. echo substr($str, 2); //mop.com
  4. echo substr($str, 2,3); //mop
  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都支持的

相关文章

相关下载

网友评论

我要评论...
    没有更早的评论了
    取消