Is there an official PHP function to do this? 开发者_开发百科 What is this action called?
No, there is no built-in function, but you can of course build your own:
function str_truncate($str, $length) {
if(strlen($str) <= $length) return $str;
return substr($str, 0, $length - 3) . '...';
}
function truncateWords($input, $numwords, $padding="") {
$output = strtok($input, " \n");
while(--$numwords > 0) $output .= " " . strtok(" \n");
if($output != $input) $output .= $padding;
return $output;
}
Truncate by word
No, PHP does not have a function built-in to "truncate" strings (unless some weird extension has one, but it's not guaranteed the viewers/you will have that sort of plugin -- I don't know of any that do).
I would recommend just writing a simple function for it, something like:
<?php
function truncate($str, $len)
{
if(strlen($str) <= $len) return $str;
$str = substr($str, 0, $len) . "...";
return $str;
}
?>
And if you'd like to use a "suspension point" character (a single character with the three dots; it's unicode), use the HTML entity …
.
I use a combination of wordwrap, substr and strpos to make sure it doesn't cut off words, or that the delimiter is not preceded by a space.
function truncate($str, $length, $delimiter = '...') {
$ww = wordwrap($str, $length, "\n");
return substr($ww, 0, strpos($ww, "\n")).$delimiter;
}
$str = 'The quick brown fox jumped over the lazy dog.';
echo truncate($str, 25);
// outputs 'The quick brown fox...'
// as opposed to 'The quick brown fox jumpe...' when using substr() only
精彩评论