<echo $this->Text->truncate(strip_tags($news['Newspost']['article_' . $lang]), 200, array('ending' => ' ...', 'exact' => false, 'html' => true));>
我们目前正在我们的网站上使用此功能在我们的主页上创建新闻邮件的预览。 当新闻邮件包含太多CAPITALS或宽度较大的符号(@#...)时,截断不能正常工作,并显示一条额外的行。
一种解决方案就是缩短截断值,但对于普通帖子来说这看起来不太好。
最好的方法是什么? 页面上有大约10-20个这样的帖子,重要的是我们网站上有很多同时用户(100-500)。 所以我不想添加一些奇怪的东西,这会使网站放慢太多。
答案 0 :(得分:0)
<?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 ...
*/
?>
从字符串中获取大写百分比,并按百分比大小应用截断
ex1:大写= 10%只显示50个字符
ex2:大写= 21%只显示33个字符......