<echo $this->Text->truncate(strip_tags($news['Newspost']['article_' . $lang]), 200, array('ending' => ' ...', 'exact' => false, 'html' => true));>
我们目前正在网站上使用它来在我们的主页上创建新闻发布的预览。当新闻发布中包含太多的大写字母或宽度较大的符号(@#...)时,截断将无法正常工作,并显示多余的一行。
一种解决方案是仅仅缩短截短时间,但这对于普通帖子来说看起来并不好。
最好的方法是什么?一个页面上大约有10-20个帖子,重要的是,我们的网站上有很多同时用户(100-500)。因此,我不想添加一些奇怪的东西,这些东西会使网站的运行速度大大降低。
<?php
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
function truncate_str($str, $limit=30) {
if( $limit < 3 ) $limit = 3;
if( strlen($str) > $limit ) return substr($str, 0, $limit - 3) . ' ...';
return $str;
}
function showTextByCapitalPercent($percent,$str) {
$int_percent = (int)$percent;
// 0-24% capitals
if( in_array($int_percent,range(0,24) ) ) {
return truncate_str($str, $limit=50)."\n";
}
// 25-49% capitals
if( in_array($int_percent,range(25,49) ) ) {
return truncate_str($str, $limit=40)."\n";
}
// 50-74% capitals
if( in_array($int_percent,range(50,74) ) ) {
return truncate_str($str, $limit=30)."\n";
}
// 75-100% capitals
if( in_array($int_percent,range(75,100) ) ) {
return truncate_str($str, $limit=20)."\n";
}
return '';
}
$str1 = "Lorem ipsum dolor sit Amet, consectetur adipiscing elit. ";
$str2 = "Fusce eu mauris libero. Morbi auctor lobortis ex, pulvinar fermentum massa. ";
$str3 = "Cras DOLOR IPSUM, CONGUE EU ornare VITAE, egestas SED URNA. ";
$str4 = "Nunc NEC urna MOLLIS, rutrum nisi eu, bibendum turpis.";
$percent_capitals_str1 = (count_capitals($str1)*100)/strlen($str1);
$percent_capitals_str2 = (count_capitals($str2)*100)/strlen($str2);
$percent_capitals_str3 = (count_capitals($str3)*100)/strlen($str3);
$percent_capitals_str4 = (count_capitals($str4)*100)/strlen($str4);
echo "<pre>";
echo "capitals str1: ".$percent_capitals_str1."%\n";
echo "capitals str2: ".$percent_capitals_str2."%\n";
echo "capitals str3: ".$percent_capitals_str3."%\n";
echo "capitals str4: ".$percent_capitals_str4."%\n";
echo "\n-------------------------\n";
echo "str1: ".showTextByCapitalPercent($percent_capitals_str1,$str1)."\n";
echo "str2: ".showTextByCapitalPercent($percent_capitals_str2,$str2)."\n";
echo "str3: ".showTextByCapitalPercent($percent_capitals_str3,$str3)."\n";
echo "str4: ".showTextByCapitalPercent($percent_capitals_str4,$str4)."\n";
/*
out
capitals str1: 3.5087719298246%
capitals str2: 2.6315789473684%
capitals str3: 51.666666666667%
capitals str4: 18.518518518519%
-------------------------
str1: Lorem ipsum dolor sit Amet, consectetur adipisc ...
str2: Fusce eu mauris libero. Morbi auctor lobortis e ...
str3: Cras DOLOR IPSUM, CONGUE EU ...
str4: Nunc NEC urna MOLLIS, rutrum nisi eu, bibendum ...
*/
?>
从字符串中获取资本百分比,并按百分比大小应用截断
例1:大写= 10%仅显示50个字符
例2:大写= 21%仅显示33个字符....
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句