I found myself needing this function, and was wondering if it exists in PHP already.
我发现自己需要这个功能,并且想知道它是否已经存在于PHP中。
/**
* Truncates $str and returns it with $ending on the end, if $str is longer
* than $limit characters
*
* @param string $str
* @param int $length
* @param string $ending
* @return string
*/
function truncate_string($str, $length, $ending = "...")
{
if (strlen($str) <= $length)
{
return $str;
}
return substr($str, 0, $length - strlen($ending)).$ending;
}
So if the limit is 40 and the string is "The quick fox jumped over the lazy brown dog", the output would be "The quick fox jumped over the lazy brow...". It seems like the sort of thing that would exist in PHP, so I was surprised when I couldn't find it.
因此,如果限制是40并且字符串是“快速狐狸跳过懒惰的棕色狗”,输出将是“快速狐狸跳过懒惰的眉毛......”。这似乎是PHP中存在的那种东西,所以当我找不到它时我感到很惊讶。
4 个解决方案
#1
No it does not exist. Many libraries provide it however as you're not the first to need it. e.g. Smarty
不,它不存在。然而,许多图书馆提供它,因为您不是第一个需要它的人。例如Smarty的
#2
$suffix = '...';
$maxLength = 40;
if(strlen($str) > $maxLength){
$str = substr_replace($str, $suffix, $maxLength);
}
Your implementation may vary slightly depending on whether the suffix's length should be count towards the total string length.
您的实现可能略有不同,具体取决于后缀的长度是否应计入总字符串长度。
#3
Here's the one line version for those interested
这是感兴趣的人的单行版本
<?php
echo (strlen($string) > 40 ? substr($string, 0, 37)."..." : $string);
?>
#4
It doesn't.
#1
No it does not exist. Many libraries provide it however as you're not the first to need it. e.g. Smarty
不,它不存在。然而,许多图书馆提供它,因为您不是第一个需要它的人。例如Smarty的
#2
$suffix = '...';
$maxLength = 40;
if(strlen($str) > $maxLength){
$str = substr_replace($str, $suffix, $maxLength);
}
Your implementation may vary slightly depending on whether the suffix's length should be count towards the total string length.
您的实现可能略有不同,具体取决于后缀的长度是否应计入总字符串长度。
#3
Here's the one line version for those interested
这是感兴趣的人的单行版本
<?php
echo (strlen($string) > 40 ? substr($string, 0, 37)."..." : $string);
?>
#4
It doesn't.