Posted by & filed under Programming.

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;
}

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

  1. 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..."

    Reply
  2. 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

    Reply
    • Ryan

      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.

      Reply
  3. Auto liker

    whoah this blog is great i love studying your posts.
    Keep up the great work! You recognize, many individuals
    are searching round for this information, you can help
    them greatly.

    Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>