HOW-TO: Use PHP's Substr Function To Truncate Long Strings and Add Ellipsis
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.




Follow Technorati