Skip to content

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.

function shorten_string($string, $wordsreturned)
/*	Returns the first $wordsreturned out of $string.  If string
contains fewer words than $wordsreturned, the entire string
is returned.
*/
{
$retval = $string;		//	Just in case of a problem

$array = explode(" ", $string);
if (count($array)<=$wordsreturned)
/*	Already short enough, return the whole thing
*/
{
$retval = $string;
}
else
/*	Need to chop of some words
*/
{
array_splice($array, $wordsreturned);
$retval = implode(" ", $array)." ...";
}
return $retval;
}
Published inProgramming

21 Comments

  1. Michael Michael

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

    • surendra surendra

      Very usefull

  2. Luke Luke

    Thanks!

    Very useful.

  3. bogatyr bogatyr

    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 Tom Something

    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 Tom Something

    …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. Amr Amr

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

  11. Shailendra Shailendra

    Nice Function..

  12. That’s exactly what I need. Thanks Ryan! ^_^

  13. surendra surendra

    thnx

  14. Ted Ted

    Perfect! Thank you very much, though there is a bug in a code on line: 10. There must be as follows: if (count($array) == $wordsreturned)

    Thanks

    • The &lt; that was there was from WordPress trying to format. It shouldn’t be == though. Let’s say that you want no more than 20 words, but the string only has 5. The if wouldn’t fire to catch that it doesn’t need to do anything.

  15. Ajay Ajay

    Thanks A lot!!!!……………….

  16. Use substr function in PHP

    • $string = substr($string,0,25);

    • substr would give you the first 25 characters. This gives you the first X words.

Leave a Reply

Your email address will not be published. Required fields are marked *