Technology

PHP: Cut your excerpt off at the word using strrpos

If you’re working with PHP and you want to only show an excerpt from your source text and cut it off at a number of characters, your excerpt can look ugly if it’s done mid-string. I had to write a function to do this in ASP and in ASP.NET that basically cycled from the last character back to find the last space and cut it off there. Kind of nasty and a little bit of overkill. You can actually see this in action on my home page where I only provide the first 500 characters.

I was fully prepared to develop the same function with PHP today but found (as usual) that PHP had a function that does it already, strrpos.

The old code will take a substring ($content) from the first character to the maximum number of characters you want ($maxchars):
$content = substr($content, 0, $maxchars);
echo $content;

The new code:
$content = substr($content, 0, $maxchars);
$pos = strrpos($content, " ");
if ($pos>0) {
$content = substr($content, 0, $pos);
}
echo $content;

So the new code first cuts off the content at the character limit you’re looking for. However, the next step is to look for the last space (” “) in the content. $pos will wind up being that position. Now, I simply ensure that there actually is a space in the content by asking if $pos>0. If there’s not, it will just cut the content off at the number of characters I’ve requested. If there is any space, it will gracefully cut my content off at the space.

This is a nice way of using the combination of the maximum number of characters and the cutting it off at the word. Hope you like!

And I’m sure I’ll find out if there’s an ASP.NET function that does this… I couldn’t find one.

7 Comments

  1. 1
  2. 2
  3. 3
  4. 4

    If $content is initially SHORTER than $maxchars the code as written will still look right to left for a space and cut out the last word. You can either concatenate a space at the end of $content, or do an if (strlen()…)

  5. 5

    This seemed to work as a function (addressing the previous comment):

    function showexcerpt($content, $maxchars) {

    if (strlen($content) > $maxchars) {

    $content= substr($content, 0, $maxchars);
    $pos = strrpos($content, " ");

    if ($pos>0) {
    $content = substr($content, 0, $pos);
    }

    return $content . "…";

    } else {

    return $content;

    }

    }

  6. 6

    What if our final character is a punctuation character like a full-stop, exclamation mark or question mark?  Unfortunately, this code will wipe the entire word preceding said punctuation character.  

    I think you’d be better off writing something a little more robust.

  7. 7

Leave a Reply