Excerpt
When you start about building your own blogging/CMS systems, you’ll normally run into the need for an excerpt system. Sure you could use a whole new field in your database to handle it, but sometimes, it’s just easier to grab a bit of text from your post and use that.
However, doing it so that you don’t cut off mid word can be a bit of a challenge. Luckily for us, PHP has a few great functions, that while on their own seem fairly useless, combined gives us exactly what we are looking for.
<<?php function excerpt($message,$size = 100){ (!is_int($size))?100:$size; $message = substr($message,0,$size); $message = substr($message,0,strrpos($message,' ')); return $message.' ...'; } ?>
This function will accept the string you want to make an excerpt out of as well as an optional size variable. This will tell us how large we want the excerpt to be. Because of the nature of this function, the resulting excerpt will not always be 100 characters, but it will be as close as it can to it without going over.
The first check we do is to make sure that the size passed to our function is actually an integer. If it is not, then we simply set it back to our default of 100. These are known as conditional statements, and if we broke it out it would really just be
if(!is_int($size)) $size = 100; else $size = $size;
Which is just too long for what we need.
The next line actually takes our string and chops it off at 100 characters using the substr() function. Using this function we pass our string as the first parameter, the start location (0 in this case, because we want to start at the beginning of the string) and the length of the string we need.
The last line of our function is a little more complicated than the rest. Once again we are using the substr() function, but this time as our third argument is actually the position of the last occurring ” ” (space) in our new substring. This is done using the built in function strrpos() This function takes a string, and a delimiter, and looks for the limiter starting at the end of the string. If it encounters it, it returns an integer value of its position. This ensures that the last character is actually a space.
Finally we return the new $message value.

Powered by ScribeFire.

