Shorten a string & add an ellipsis – PHP

Shorten a string & add an ellipsis - PHPWhether 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 hinting that there is more text to follow.

So you want to shorten a string?

Shortening or constraining the length of a string is very easily done with PHP. All you have to do is call upon substr():

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

This would echo out as:

Shorten a string

15 characters, including spaces are counted from the beginning of the string (character 0). Now, let’s add the ellipsis:

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

That was very simple. I have added the ellipsis the end of the string. You could also use &#0133 for an html friendly ellipsis.

Now, 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 amount of characters and both applies the substr() and adds an ellipsis only if the total equals over 11 characters:

$my_string = "I can go on and on and on and on";
if(strlen($my_string ) > 11)
	$string = substr($my_string, 0, 11)."...";

I think it’s time we put all of this into an easy-to-manage function:

function shorten_string($string, $amount)
	 if(strlen($string) > $amount)
		$string = trim(substr($string, 0, $amount))."...";
	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(). And to use our function:

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

This would give us:

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

Leave a Reply

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