最新消息:

PHP函数第14款:utf-8中文截取,单字节截取模式,1个中文字节为2个英文字节 cn_substr_utf8

PHP扩展函数 杨红伟 4178浏览 0评论

一:函数简介

我们都知道,在中文当中分为gb2312和utf8,对它们截取的方法是不同的。本文中要讲的就是对utf8字符的截取方式,该函数看似简单,笔者在网上也找了一部分,后来发现dedecms中对很多函数的处理都非常严谨,当然本文中所采用的 cn_substr_utf8 函数就是用 dedecms 中的。当然,我们以还会讲到 对 gb2312 字符的处理,以及对传入参数的处理!

演示地址: http://www.ijquery.cn/phpfunction/cn_substr_utf8/demo1.php

下载地址: http://www.ijquery.cn/phpfunction/cn_substr_utf8/cn_substr_utf8.zip

二:函数说明及应用

echo cn_substr_utf8("中华人民共和国",10);

返回的结果是:

中华人民共

三:函数代码

/**
 *  utf-8中文截取,单字节截取模式,1个中文字节为2个英文字节
 *
 * @access    public
 * @param     string  $str  需要截取的字符串
 * @param     int  $slen  截取的长度,
 * @param     int  $startdd  开始标记处,默认从0开始
 * @return    string
 */
if ( ! function_exists('cn_substr_utf8'))
{
	function cn_substr_utf8($str, $length, $start=0)
	{
		if(strlen($str) < $start+1)
		{
			return '';
		}
		preg_match_all("/./su", $str, $ar);
		$str = '';
		$tstr = '';

		//为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
		for($i=0; isset($ar[0][$i]); $i++)
		{
			if(strlen($tstr) < $start)
			{
				$tstr .= $ar[0][$i];
			}
			else
			{
				if(strlen($str) < $length + strlen($ar[0][$i]) )
				{
					$str .= $ar[0][$i];
				}
				else
				{
					break;
				}
			}
		}
		return $str;
	}
}

四:函数图片


Warning: Use of undefined constant PRC - assumed 'PRC' (this will throw an Error in a future version of PHP) in /www/wwwroot/www.ijquery.cn/wp-content/themes/d8-3.0/comments.php on line 17
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址