Web Development with PHP, HTML, CSS, & JavaScript

Displaying a shortened Block of Text with PHP

Monday 16th November 2009

From time to time, I find myself wanting to display a certain amount of text, like and intro or snippet, from a much larger one. This could be a description or intro for an article, or news item for use on a landing page or latest news widget. For dynamic websites, where content is pulled in automatically from a database, this could cause a bit of problem. The following is a short snippet of PHP code that I use when I want to take a substring of a large chunk of text, and return a specified number of words from the beginning.

//$string: the initial, large chunk of text
//$newstring: smaller portion that you want to display
//$numchars is the max number of characters for the new string
$numchars = 200;
$newstring = preg_replace('/\s+?(\S+)?$/', '',
substr($string, 0, $numchars));

We set our variable $numchars to the maximum number of characters that we want to return. This could be something like 25 for a news headline, or 200 or 300 for a description/intro for a news articles or blog entry.

Now to break down the code:

substr($string, 0, $numchars));

This takes in the initial string, and returns the first $numchars characters. However, this doesn't account for words, it just cuts the string, which could leave you with a piece of text that stops in the middle of a word. To solve this problem, we use the preg_replace function:

preg_replace('/\s+?(\S+)?$/', '', $astring);

This line uses regular expressions to find the last instance of a non-breaking space, and truncates the string at that point. In essence, it cuts off the last incomplete word in the string.

So together:

$newstring = preg_replace('/\s+?(\S+)?$/', '', 
substr($string, 0, $numchars));

This shortens your input string to the specified number of characters, and then returns all the words in the new string until the last space. And there it is: a quick, useful and powerful little bit of PHP that can help building and maintaining dynamic websites a lot easier. And this can be combined with more PHP code to strip html tags from the output.

Filed under: