PHP初记|中英混合字符串截取

WBOY
Release: 2016-06-13 13:08:25
Original
899 people have browsed it

PHP小记|中英混合字符串截取

常常在WEB页面显示记录列表的时候需要对过长内容进行截取。

采用PHP内置的substr函数对中英混合字符串,特别是字符编码在UTF-8的情况下,支持非常不好,会出现乱码。

所以自己写了一个函数:

?

function truncate($string, $len, $wordsafe = FALSE) {
	$slen = strlen($string);
	if ($slen <= $len) {
		return $string;
	}
	if ($wordsafe) {
		while (($string[-- $len] != ' ') && ($len > 0)) {
		};
	}
	if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
		return substr($string, 0, $len) . "...";
	}
	while (ord($string[-- $len]) < 0xC0) {
	};
	return substr($string, 0, $len) . "...";
}
Copy after login

?

经测试成功。YEAH!

?

=======================================================================

2012-06-15更新:

?

今天再次写了一个,好处是会把两个英文字符当作一个汉字字符的长度:

所以传递的需要截取多少个汉字的长度

?

?

function truncate($string, $len, $cnCharWidth = 2) {

	$len = $len * $cnCharWidth;
	$suffix = "...";
	$newStr = "";

	for ($i = 0, $j = 0; $i < $len; $i++, $j++) {

		if (!isset($string[$j])) {
			$suffix = "";
			break;
		}

		$start = $j;
		while ($j < ($start +3) && !(ord($string[$j]) < 0x80)) {
			$j++;
		}
		if ($start == $j) {
			$charLen = 1;
		}
		else {
			$i = $i + 1;
			$j--;
			$charLen = 3;
		}

		$newStr .= substr($string, $start, $charLen);
	}

	return $newStr . $suffix;
}
Copy after login
Related labels:
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!