PHP: A function to return the first n words from a string

Do you ever find yourself needing to shorten a string in PHP? Maybe return the first 25 words of a long story? Give this routine a try. It will return the first n words from a string, or the entire string if it is less than n words long.

PHP:
  1. function shorten_string($string, $wordsreturned)
  2. /*  Returns the first $wordsreturned out of $string.  If string
  3. contains fewer words than $wordsreturned, the entire string
  4. is returned.
  5. */
  6. {
  7. $retval = $string;    //    Just in case of a problem
  8.  
  9. $array = explode(" ", $string);
  10. if (count($array)<=$wordsreturned)
  11. /*  Already short enough, return the whole thing
  12. */
  13. {
  14. $retval = $string;
  15. }
  16. else
  17. /*  Need to chop of some words
  18. */
  19. {
  20. array_splice($array, $wordsreturned);
  21. $retval = implode(" ", $array)." ...";
  22. }
  23. return $retval;
  24. }

Bookmark and Share

Post Info

10 Responses to “PHP: A function to return the first n words from a string”

  1. Thanks. Very usefull. Just cut n pasted into my program and ran.

  2. Thanks!

    Very useful.

  3. Just saved me that much work. Much thanks.

  4. I’ll definately drink a sip of beer for your health. Thanks for the function ;)

  5. Tom Something on March 12th, 2009 at 6:57 pm

    Thanks. Short and simple is the way to go, and now I have a practical example of array_splice to do other stuff with.

    Noticed a small typo in your inline comment:

    “If string contains more words than $wordsreturned, the entire string is returned.”

    should probably read “Unless string contains…”

    of “If string contains <= $wordsreturned…”

  6. Tom Something on March 12th, 2009 at 6:58 pm

    …aaaaand a typo in my own comment. Go me!

  7. Thanks. You’re right, it should be if string contains fewer words then…

  8. This is really helpful. I had to pick up first name of the user and it worked like charm

  9. Here go another way:

    function first_word()
    {
    preg_match(‘/[^ ]*/’, $username, $matches);
    return $matches[0];
    }

  10. Great work.
    I was looking for such function.
    Thank you very much

Leave a Reply