我的功能有一定的长度,但我喜欢用它。我将字符串int转换为数组。
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
或者如果文本来自编辑器并且您想要去掉HTML标记。
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
可能的重复http://stackoverflow.com/q/15705059/ – HamZa 2013-04-29 12:37:23
不,我没有使用正则表达式。 – imulsion 2013-04-29 12:38:28
接受的答案不是正则表达式的解决方案:) – HamZa 2013-04-29 12:38:53