Is there an official PHP function to do this? What is this action called?
Asked
Active
Viewed 153 times
1
-
3Some call it truncating, some call it excerpting... but sadly PHP has no built-in function for this :( – BoltClock Dec 17 '10 at 20:31
-
Possible duplicate: http://stackoverflow.com/questions/4446034 – Jonah Dec 17 '10 at 20:33
-
What's wrong with `$string = substr($string, 0, 50) . '...';`? – Jonah Dec 17 '10 at 20:35
-
That you need `if (strlen($string) > 50) { $string = substr($string, 0, 47)."..."; }`. – user502515 Dec 17 '10 at 20:38
-
@Jonah, that works, but also cuts off words. Just something to be cautious of, especially on corporate sites. ;) – simshaun Dec 17 '10 at 20:38
-
@simshaun: Then see my first comment. – Jonah Dec 17 '10 at 20:42
-
PHP isn't intended to do this. CSS is. – Your Common Sense Dec 17 '10 at 20:52
4 Answers
3
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) . '...';
}

Jacob Relkin
- 161,348
- 33
- 346
- 320
-
1Some strings, when lacking the last three chars, will end in a space. This isn't desired, since you don't want your "..." appearing as " ..." Something that should be considered. Other than that, +1. – Sampson Dec 17 '10 at 20:45
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

John Giotta
- 16,432
- 7
- 52
- 82
1
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 …
.

Qix - MONICA WAS MISTREATED
- 14,451
- 16
- 82
- 145
1
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

netcoder
- 66,435
- 19
- 125
- 142