很可惜,wordpress不支持字符串输出长度控制功能,我们在做标题输出的时候,有时候会因为标题过长而导致换行而影响美观,所以有必要手动增加字符串截取功能.

/*
$strs:原始字符串,即你需要截取长度的字符串,比如标题,文章标题链接等
$strLength:你需要截取字符串的长度,该长度为中文字符长度.
$startIndex:从哪个位置截取字符串,如无特殊情况,一般从0开始.
$strCode:编辑格式,推荐用UTF-8
*/
function subStrings($strs, $strLength, $startIndex = 0, $strCode = ‘UTF-8’)
{
if($strCode == ‘UTF-8’)
{
$pa = “/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/”;
preg_match_all($pa, $strs, $t_string);

if(count($t_string[0]) – $startIndex > $strLength) return join(”, array_slice($t_string[0], $startIndex, $strLength)).”…”;
return join(”, array_slice($t_string[0], $startIndex, $strLength));
}
else
{
$startIndex = $startIndex*2;
$strLength = $strLength*2;
$strlen = strlen($strs);
$tmpstr = ”;

for($i=0; $i< $strlen; $i ) { if($i>=$startIndex && $i< $startIndex && $i<$strLength) { if(ord(substr($strs, $i, 1))>129)
{
$tmpstr.= substr($strs, $i, 2);
}
else
{
$tmpstr.= substr($strs, $i, 1);
}
}
if(ord(substr($strs, $i, 1))>129) $i ;
}
if(strlen($tmpstr)< $strlen ) $tmpstr.= "..."; return $tmpstr; } } 调用方法: 例如标题为"一二三四五六七八九十",我们想截取前6个字,即只输出"一二三四五六",那么: $caption="一二三四五六七八九十"; $subcaption=subStrings($caption,6,0,'UTF-8');

做人要厚道,转载请注明文章来源: https://www.boxui.com/share/761.html