Ben
Ben

Reputation: 62444

Shortening a string with ... on the end

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

Upvotes: 1

Views: 157

Answers (4)

netcoder
netcoder

Reputation: 67735

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

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163288

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

Upvotes: 3

John Giotta
John Giotta

Reputation: 16964

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

Upvotes: 2

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

Upvotes: 1

Related Questions