Shortening a string with … on the end

2019-08-09 04:03发布

问题:

Is there an official PHP function to do this? What is this action called?

回答1:

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) . '...';
}


回答2:

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



回答3:

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 &hellip;.



回答4:

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