HOW-TO: Use PHP's Substr Function To Truncate Long Strings and Add Ellipsis

Author: Jeremy Dowell
Published: August 31, 2010 at 6:02 pm
Share

 

So, let's say you have a long string in a variable named $foo, and an empty variable named bar:

$foo = "HOW-TO: Use PHP's substr function to truncate long strings and add ellipsis";
$bar = "";

and let's say you wanted to cut that string down to forty characters so that the output would be:

"HOW-TO: Use PHP's substr function to tru"

To do this, we use a single PHP command called substr

The syntax for substr is as follows:
substr(string,starting index,number of characters (optional));

Since we want to start at the beginning of the string, we'll use 0 as the starting index because, as all arrays, it begins at index 0, instead of 1. For number of character's we'll use 40, because that's how many we want.

So the actual code looks like:
$bar = substr($foo,0,40);
echo $bar; // "HOW-TO: Use PHP's substr function to tru"

But, I promised I'd show you how to add an ellipsis:
$bar = substr($foo,0,40) . "...";
echo $bar; // "HOW-TO: Use PHP's substr function to tru..."

Want to see it in action?

Look at the breadcrumb at the top of this page.

 
 

About this article

Article Tags

Share: Bookmark and Share

Add your comment, speak your mind

Personal attacks are NOT allowed
Please read our comment policy