Skip to content

PHP function to get first n words from a string

A handy little function for your bag of tricks. This PHP function will return a max number of words out of a string, or the whole string if it’s already shorter.

/**
 * Returns the first $wordsreturned out of $string.  If string
 * contains more words than $wordsreturned, the entire string
 * is returned.
 * @param String $string The string to check
 * @param int $wordsreturned Max number of words to include
 */
function shorten_string($string, $wordsreturned)

{
    $retval = $string;
    $array = explode(' ', $string);
    if (count($array)<= $wordsreturned) {
        $retval = $string;
    }
    else {
        array_splice($array, $wordsreturned);
        $retval = implode(' ', $array).' ...';
    }
    return $retval; 
}

This probably could be made shorter, but I was in a hurry when I needed this and went for quick rather than clever.

Published inProgramming

One Comment

Leave a Reply

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