PHP截取指定长度的字符串,超出部分用 ..替换

 
  
function substr_format($text, $length, $replace='..', $encoding='UTF-8') 
{
	if ($text && mb_strlen($text, $encoding)>$length)
	{
		return mb_substr($text, 0, $length, $encoding).$replace;
	}
	return $text;
}

还有
 
  
function cut_string($str, $len)
{
	// 检查长度
	if (mb_strwidth($str, 'UTF-8')<=$len)
	{
		return $str;
	}


	// 截取
	$i 		= 0;
	$tlen 	= 0;
	$tstr 	= '';

	while ($tlen < $len)
	{
		$chr 	= mb_substr($str, $i, 1, 'UTF-8');
		$chrLen = ord($chr) > 127 ? 2 : 1;

		if ($tlen + $chrLen > $len) break;

		$tstr .= $chr;
		$tlen += $chrLen;
		$i ++;
	}

	if ($tstr != $str)
	{
		$tstr .= '...';
	}

	return $tstr;
}


你可能感兴趣的:(PHP技术)