Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Shorten String for Preview

Shorten String for Preview

Shorten a string and add '...' to it. Used to display a preview of content on your site.

Simply create a function that will produce this effect simply by calling it over and over again.

function truncateString($str, $max, $rep = '...') {
  if(strlen($str) > $max) {
    $leave = $max - strlen($rep);
    return substr_replace($str, $rep, $leave);
  } else {
    return $str;
  }
}

Let's walk through the function and explain what is going on. We have the 3 arguments. The string to truncate, a length and replacement character pre set so it isn't a required argument.

Check to see if the length of the string is greater than our max length $max using strlen() which returns the length of a string. If it is less then max we simply return the string and leave the function.

Now assuming the string is longer than our max length we fill a variable to store our new length which is the max length minus the length of the replacement suffix. Then finally we return our string with the suffix added using substr_replace which replaces text with a portion of a string.

Here is an example call with the complete function for easy copy & pasting.

function truncateString($str, $max, $rep = '...') {
  if(strlen($str) > $max) {
    $leave = $max - strlen($rep);
    return substr_replace($str, $rep, $leave);
  } else {
    return $str;
  }
}

print truncateString("Here is my faux really long string", 10);

That example would result in the following. Kind of small but this is just an example.

Here is...

That's it, now you can truncate "shorten" your strings until your hearts content.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Shorten String for Preview

 Thomas (iplayguitar214)  Mon Oct 23, 2006 8:53 pm  
hmm, nice, never really thought to put it in a function considering it's only a few lines of code, but it's definately a good idea.
 mkeefe  Sun Feb 25, 2007 12:32 am  
Thanks Thomas, I try to keep everything in nice little compartments. That way I can make changes and everything rolls with the change.

In a bigger project I would make this a method inside of a Utils subclass but wanted to keep this example simple and to the point.
 Jhecht  Fri Jun 8, 2007 10:25 pm  
My only issue with things like that is when your String value has HTML. Then let's say we have a string like this:

So this is a string with some HTML Elements and if we Substr this wrong, things go horribly, horribly wrong in the rest of the code.

Lets say that i want to show a 40 character preview, including spaces and so on. Using the function above this(or something like it) would happen :
So this is a string with some HTML

Bad part about that: There's no closing tag for the . Meaning that every text after the opening HTML is going to be italisized(sp?)
 peja  Sun Jan 6, 2008 2:56 pm  
This is a function I came up with, that takes HTML tags and entities into account. Enjoy :)

function html_truncate($text, $max, $ending = '...') {
$max = $max - strlen($ending);
$done = false;
$entity = false;
$tag = false;
$out = "";
$outCnt = 0;
$textCnt = strlen($text);

for ($i = 0; $i < $textCnt; $i++) {
if ($entity) {
if (!$done) $out .= $text[$i];
if ($text[$i] == ';') $entity = false;

} else if ($tag) {
$out .= $text[$i];
if ($text[$i] == '>') $tag = false;

} else {
switch ($text[$i]) {
case '<': $tag = true; $out .= $text[$i]; break;
case '&': $entity = true; /*break;*/
default:
if (!$done)
if ($outCnt < $max) {
$out .= $text[$i];
$outCnt++;
} else {
$done = true;
$out .= $ending;
}
}

}
}

return $out;
}
 peja  Sun Jan 6, 2008 3:06 pm  
Important note: The function above doesn't work well for UTF-8 string...
 Anonymous  Mon Feb 25, 2008 4:11 am  
With your script, if you put ("Hello, World!", 5)
it would display: Hel... If you want to put 5 characters from the string and display: Hello... it is simple... At the start of the script put $max = $max + strlen($rep);
eg:
function truncateString($str, $max, $rep = '...') {
$max = strlen($rep);
if(strlen($str) > $max) {
$leave = $max - strlen($rep);
return substr_replace($str, $rep, $leave);
} else {
return $str;
}
}
print truncateString("Hello, World!", 5);

so it max was the value of $max plus the number of characters in $rep!
--Anonymous
 Sinterklaas  Mon Jun 16, 2008 8:46 am  
Just looking for some code to shorten my strings isn't there an easy way to do it.... without this much code

Some thing like:
$myvar = abcdefg;
substr('$myvar', 0, 2);
echo $myvar;

or something like that?!?



 mkeefe  Mon Jun 16, 2008 9:36 am  
@Sinterklaas - Yes, that would be for when you simply want to shorten a string. This example appends an ellipsis "..." to a string when it reaches a certain length.
 Greg  Thu Mar 19, 2009 7:23 pm  
Well,

$myvar = abcdefg;
echo substr($myvar, 0, 2).'…';


Problem solved.
 mkeefe  Fri Mar 20, 2009 12:08 am  
@Greg - Problem is if the string is not longer than the limit you will have a complete string with an ellipsis at the end, no matter what.
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles