php截取字符串
来源:互联网 发布:mysql存储过程加法 编辑:程序博客网 时间:2024/05/08 22:41
1.substr(源字符串,其实位置[,长度])-截取字符串返回部分字符串
(2)截取utf8编码的多字节字符串
(3)支持 utf-8、gb2312都支持的汉字截取函数
转载请注明地址: http://www.phpddt.com/php/366.html 尊重他人劳动成果就是尊重自己!
<?php $str ="phpddt.com"; echo substr($str, 2); //pddt.com echo substr($str, 2,3); //pdd echo substr($str, -2); //om 负数从结尾开始取 ?>
但是当你截取中文字符串的时候很容易出现乱码,因为一个汉字是两个字节,而一个英文字母是一个字节。解决办法如下:
2.mb_substr(),使用方法和substr相同,不过要开启php.ini里面extension=php_mbstring.dll扩展,不用担心,一般的空间商
都会开启这个扩展的。
<?php echo mb_substr("php点点通", 1,3,"UTF-8"); //hp点 ?>
网上也有很多中文字符串截取教程,实现起来比较复杂,感觉还是用php自带的函数实现起来比较好。整理的网络资料(php代码)如下:
(1)截取GB2312中文字符串
<?php //截取GB2312中文字符串 function mysubstr($str, $start, $len) { $tmpstr = ""; $strlen = $start + $len; for($i = 0; $i < $strlen; $i++) { if(ord(substr($str, $i, 1)) > 0xa0) { $tmpstr .= substr($str, $i, 2); $i++; } else $tmpstr .= substr($str, $i, 1); } return $tmpstr; } echo mysubstr("php点点通", 1, 5); //php点 ?>
(2)截取utf8编码的多字节字符串
<?php //截取utf8字符串 function utf8Substr($str, $from, $len) { return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'. '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s', '$1',$str); } echo utf8Substr("php点点通", 1, 5); //hp点点通 ?>
(3)支持 utf-8、gb2312都支持的汉字截取函数
<?php //同时支持 utf-8、gb2312都支持的汉字截取函数 ,默认编码是utf-8 function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') { if($code == 'UTF-8') { $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]/"; preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."..."; return join('', array_slice($t_string[0], $start, $sublen)); } else { $start = $start*2; $sublen = $sublen*2; $strlen = strlen($string); $tmpstr = ''; for($i=0; $i<$strlen; $i++) { if($i>=$start && $i<($start+$sublen)) { if(ord(substr($string, $i, 1))>129) { $tmpstr.= substr($string, $i, 2); } else { $tmpstr.= substr($string, $i, 1); } } if(ord(substr($string, $i, 1))>129) $i++; } if(strlen($tmpstr)<$strlen ) $tmpstr.= "..."; return $tmpstr; } } $str = "php点点通提供原创php教程"; echo cut_str($str, 8, 0); //php点点通提供... ?>
转载请注明地址: http://www.phpddt.com/php/366.html 尊重他人劳动成果就是尊重自己!
- php 截取中文字符串
- php的字符串截取
- PHP 截取字符串专题
- PHP 截取字符串专题
- PHP截取中文字符串
- PHP 字符串截取函数
- PHP 截取字符串专题
- PHP 截取字符串专题
- PHP 截取字符串函数
- PHP 截取字符串专题
- php截取中文字符串
- PHP 字符串截取
- 字符串截取php
- PHP截取中文字符串
- php 截取字符串
- PHP截取中文字符串
- php截取字符串方法
- php截取字符串方法
- Android FM播放时拔出耳机后FM APP自动close
- 进入U盘
- 微信公众号接口开发为什么不能使用循环语句?
- linux驱动子系统--ATA存储
- 很实用的android压缩图片的算法
- php截取字符串
- Libusb中的dll引用方法
- RTP Packet 构造
- opencv学习笔记_1106
- 平时练习笔记
- TCP/IP协议簇概述
- 高效使用 SSH 的 16 个技巧
- IT项目管理的“羊肉”与“狗头”
- 10 iOS Libraries to Make Your Life Easier