Limiting text by a number of characters/words (strrpos).

posted by Danny on July 1st, 2009, in PHP | 1 Comment

If you need to display source text, but you only want to show an excerpt of it and you will probably use the function strrpos to cut your text by a number of characters. This can look ugly as it cuts the text mid-string. Beneath is a tutorial showing you how to cut your text by a certain amount of characters and at the end of the word.

Below is the full source code with comments for cutting text at the word:

 
$maxchars = 500; //Assign a maximum amount of characters
$content = substr($content, 0, $maxchars); //Cuts of the text by a specified number of characters ($maxchars).
 
$pos = strrpos($content, " "); //Looks for the last space in the text " ") and assigns the position number to $pos.
if ($pos>0) { //Asks if there is a space in the content.
$content = substr($content, 0, $pos); //If so, cut the text at $pos, therefore cutting it at the end of the word.
}
 
echo "$content..."; //Add an additional "..." to the end of your text and print it.

To alter this code to your needs, change “$content” to your source text or assign your source text to that variable. (Eg. $content =”Blah Blah Blah”;). To alter the max number of characters displayed, changeĀ  “$maxchars” to a different number.

This is a great way to chop your text neatly. Enjoy!

One Response to “Limiting text by a number of characters/words (strrpos).”

  1. ST Verschoof said...

    You make truncating Text very easy! Great job Danny!

Leave a Reply