Shorten String – Add Ellipsis [Easy PHP]

Whether you are creating a list of topics constrained to a certain character length, or want to show a brief snippet of text, then the following PHP tutorial is for you. The key is to apply as few php functions as possibly to shorten a string and tidy the resulting line with an ellipsis.

Just in case your not sure what an ellipsis is – it’s the ‘…’, enticing you to ‘read on’ or a hint that there is more text to follow.

How to shorten a string with PHP

Shortening or constraining the length of a string is very easily done with PHP. The shortening process is also know as ‘truncation’.

To truncate a string, you can to use the PHP function ‘substr()’:

<?php
$my_string = "Shorten a string if you please";
echo substr($my_string, 0, 15);
?>

The above PHP code will echo the following to your browser:

Shorten a string

As you can see, 15 characters, including spaces are counted from the beginning of the string (character 0). Additional characters are omitted. Now, let’s add the ellipsis to our string:

<?php
$my_string = "I can go on and on and on and on";
$my_string = substr($my_string, 0, 11)."...";
?>

The above will parse as:

I can go on...

As you can see, the string has been shortened and the ellipsis has been added to the end of the string. I would also recommend that you use &#0133 or &hellip; for an html friendly ellipsis, instead of three full stops.

Wouldn’t it be good if we could have this ellipsis appear only when the string is shortened? If your string data is coming from a database or any kind of array, the amount of characters within it may vary. In this case, you’ll need to add a conditional statement.

The following PHP counts the total number of characters and then applies the substr() and adds an ellipsis only if the total equals over 11 characters. I have added an additional trim() function to the string to remove any trailing spaces:

<?php
$my_string = "I can go on and on and on and on";
if(strlen($my_string) > 11)
{
	$string = trim(substr($my_string, 0, 11))."&hellip;";
}
?>

Now we can place our string shortener into an easy to manage function:

<?php
/// SHORTEN STRING...
function shorten_my_string($string, $length)
{
	if(strlen($string) > $length)
	{
		$string = trim(substr($string, 0, $length))."&hellip;";
	}
	return $string;
}
///
?>

You can see from the above, I have encased the substr() within the trim() function. This will remove any empty spaces after the effects of substr().

This is how we can use our new function:

$my_string = "I'm really starting to get the hang of this php game. I have so many ideas!";
shorten_my_string($my_string, 47);

This would parse as:

I'm really starting to get the hang of this php…

Putting any sequence of PHP into a function is always highly recommended. Especially if the code is going to be used on a regular basis.

Leave a Reply

Your email address will not be published. Required fields are marked *