When building database driven applications you often want to display leading text or a summary of another pages content on, say, an index or category page. This is often the case with Content Management Systems, blogs and article websites. When doing this recently on a small application I was building I simple used:
$descriptionSmall = substr($description, 0, 200);
I used the substr function to limit the text to the first 200 characters. This was fine until I changed the $description variable to contain a string of HTML. The would break the application as the 200th character may be in the middle of an open HTML tag. It also doesn’t look too elegant in some cases as the 200th character may be in the middle of a word.
The solution:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,50}/', strip_tags($description), $descriptionSmall);
This strips out any HTML tags from the string to only leave the text and them limits it to only 50 words!
Written by admin
Topics: web development