我在最近的PHP代码中多次需要这个功能,所以我正在寻找一个功能来完成这项工作,如果有的话......
如果字符串大于限制会截断它并放入一些遗漏文本,如...(continued)
..
就像在ruby中一样,我们在字符串
上截断了函数"And they found that many people were sleeping better.".truncate(25, :omission => "... (continued)")
我可以通过首先检查长度超过..然后修剪,然后连接...但我正在寻找类似的功能..
答案 0 :(得分: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;
}
您甚至可以编辑该功能,以便您可以选择以确切的最大长度剪切或尊重字边界...
选择基本上是你的
答案 1 :(得分: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 :(得分:0)
class StringHelper
{
public static function truncate($string, $length = 100, $append = "...")
{
if (strlen($string) <= intval($length)) {
return $string;
}
return substr($string, 0, $length) . $append;
}
}
我使用Yii框架进行截断的静态通用方法。
答案 3 :(得分:-1)
建于@OkekeEmmanuelOluchu's answer。有点短而清洁:
function truncateString($string, $length = 100, $append = "..."){
$truncated_str = substr($string, 0, $length);
$truncated_str .= strlen($string) > intval($length) ? $append : "";
return $truncated_str;
}