<?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個字符....