php 截取中文字符串实现程序
发布:smiling 来源: PHP粉丝网 添加日期:2014-07-27 15:07:05 浏览: 评论:0
在php中我们截取字符串可以使用自带的函数,但是自带的函数不支持中文截取,如果需要截取中文字符串我们需要现做一些操作,下面我来给各位朋友介绍.
针对GB2312的代码,代码如下:
- //$str是要截取的字符串
- //$start是要截取的字符的开始位置
- //$len是指要截取的字符长度
- function sub_str($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."...";
- }
针对uft8,代码如下:
- <?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);
- }
- ?>
上面的方法肯定不实用,因为我希望可以自动识别支持任何编码的字符串截取,后来找到一个还算可以的分享给各位朋友,代码如下:
- <?php
- /**
- * @package BugFree
- * @version $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $
- *
- *
- * Return part of a string(Enhance the function substr())
- *
- * @author Chunsheng Wang <wwccss@263.net>
- * @param string $String the string to cut.
- * @param int $Length the length of returned string.
- * @param booble $Append whether append "...": false|true
- * @return string the cutted string.
- */
- function sysSubStr($String,$Length,$Append = false)
- {
- if (strlen($String) < = $Length )
- {
- return $String;
- }
- else
- {
- $I = 0;
- while ($I < $Length)
- {
- $StringTMP = substr($String,$I,1);
- if ( ord($StringTMP) >=224 )
- {
- $StringTMP = substr($String,$I,3);
- $I = $I + 3;
- }
- elseif( ord($StringTMP) >=192 )
- {
- $StringTMP = substr($String,$I,2);
- $I = $I + 2;
- }
- else
- {
- $I = $I + 1;
- }
- $StringLast[] = $StringTMP;
- }
- $StringLast = implode("",$StringLast);
- if($Append)
- {
- $StringLast .= "...";
- }
- return $StringLast;
- }
- }
- $String = "www.phpfensi.com 走在中国自动化测试的前沿";
- $Length = "18";
- $Append = false;
- echo sysSubStr($String,$Length,$Append);
- ?>
Tags: php 截取中文字符串
- 上一篇:php获取网站域名与IP地址的函数
- 下一篇:php随机生成字符串程序方法总结
相关文章
- ·PHP校验ISBN码的函数(2013-11-11)
- ·PHP不缓存数据头(2013-11-11)
- ·PHP采集程序中常用的函数(2013-11-11)
- ·PHP多重判断删除文件函数(2013-11-11)
- ·php中文汉字截取函数(2013-11-12)
- ·如何用php创建与删除多级目录函数(2013-11-14)
- ·什么函数能够把文件从一个目录下转移到另外一个目录下?(2013-11-27)
- ·php_admin_value(php_admin_flag)和php_value(php_flag)(2013-11-27)
- ·使用PHP重新实现PHP脚本引擎内置函数(2013-11-27)
- ·计算一个程序的执行时间的函数(2013-11-27)
- ·php curl_init函数用法(2013-11-28)
- ·php md5 与md5_file区别详细说明(2013-11-28)
- ·php session_cache_limiter session_cache_expire等函数(2013-11-29)
- ·php var_dump简单测试(2013-11-29)
- ·php file_exists无效解决办法(2013-11-29)
- ·强大的php检查文件类型(2013-11-30)

推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)