到最近的空间
截断到目标字符最近的前一个空格。演示
$str 要截断的字符串
$chars 要剥离的字符数量,可以通过以下方式覆盖 $to_space
$to_space boolean是否从接近$chars极限的空间截断
功能
function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;
$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));
return($str . $replacement);
}
样品
$str = "this is a string that is just some text for you to test with";
print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");
?>
产量
this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--