问题
I need this functionality in my recent php code many times, So I am lookin for a function to do the work, if there exists any..
If the string if bigger than the limit truncate it and put some omission text like ...(continued)
..
Like in ruby we have truncate function on string
"And they found that many people were sleeping better.".truncate(25, :omission => "... (continued)")
I could do it by first checking the length exceeds.. then trim, then concatenation...But I am looking for some function similar..
回答1:
function substr_with_ellipsis($string, $chars = 100)
{
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
$new_string = $matches[0];
return ($new_string === $string) ? $string : $new_string . '…';
}
回答2:
function truncate($string,$length=100,$appendStr="..."){
$truncated_str = "";
$useAppendStr = (strlen($string) > intval($length))? true:false;
$truncated_str = substr($string,0,$length);
$truncated_str .= ($useAppendStr)? $appendStr:"";
return $truncated_str;
}
You could even edit the function so that you could either chose to cut at the exact maximum length or to respect word boundaries...
The choice is basically yours
回答3:
class StringHelper
{
public static function truncate($string, $length = 100, $append = "...")
{
if (strlen($string) <= intval($length)) {
return $string;
}
return substr($string, 0, $length) . $append;
}
}
Static universal method for truncate that I use with Yii framework.
回答4:
Built on @OkekeEmmanuelOluchu's answer. Little bit short and cleaner:
function truncateString($string, $length = 100, $append = "..."){
$truncated_str = substr($string, 0, $length);
$truncated_str .= strlen($string) > intval($length) ? $append : "";
return $truncated_str;
}
来源:https://stackoverflow.com/questions/10913342/php-truncate-string-if-longer-than-limit-and-put-some-omission-at-the-end-simil