Home > Backend Development > PHP Tutorial > php截取指定个数中文字符串

php截取指定个数中文字符串

WBOY
Release: 2016-06-20 13:04:01
Original
1254 people have browsed it

php截取指定个数中文字符串函数。

先上测试用的字符串:

<p><?php</p>header("Content-Type:text/html;charset=utf-8");<br /><br />echo cn_substr_utf8('我是一个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('ai\'2145m a ch3我[是一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('【我,是一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('我是一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('我是,一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('我,是,一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('我是asd一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('【我i\'m[是一,个,和哈,哦也,,国家!',12);<br />echo '<br />',cn_substr_utf8('【i\'m a ch我[是一,个,和哈,哦也,,国家!',12);<br /><p>echo '<br />',cn_substr_utf8('【i\'2145m a ch3我[是一,个,和哈,哦也,,国家!',12);</p>
Copy after login

下面是精确截取字符串的函数代码:

具体函数代码如下:

//utf-8中文截取,单字节截取模式

function cn_substr_utf8($str,$length,$append='...',$start=0){<br />	if(strlen($str)<$start+1){<br />		return '';<br />	}<br />	preg_match_all("/./su",$str,$ar);<br />	$str2='';<br />	$tstr='';<br />	//www.scutephp.com<br />	for($i=0;isset($ar[0][$i]);$i++){<br />		if(strlen($tstr)<$start){<br />			$tstr.=$ar[0][$i];<br />		}else{<br />			if(strlen($str2)<$length + strlen($ar[0][$i])){<br />				$str2.=$ar[0][$i];<br />			}else{<br />				break;<br />			}<br />		}<br />	}<br />	return $str==$str2?$str2:$str2.$append;<br />}
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template