Return to Snippet

Revision: 8398
at September 18, 2008 11:21 by Wardy


Updated Code
function shorten_string($string, $wordsreturned)
/*  Returns the first $wordsreturned out of $string.  If string
	contains more words than $wordsreturned, the entire string
	is returned.*/
{
	$retval = $string;	//	Just in case of a problem
	$array = explode(" ", $string);
	/*  Already short enough, return the whole thing*/
	if (count($array)<=$wordsreturned)
	{
		$retval = $string;
	}
	/*  Need to chop of some words*/
	else
	{
		array_splice($array, $wordsreturned);
		$retval = implode(" ", $array)." ...";
	}
	return $retval;
}

Revision: 8397
at September 18, 2008 11:18 by Wardy


Initial Code
function shorten_string($string, $wordsreturned)
/*  Returns the first $wordsreturned out of $string.  If string
	contains more 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;
	}

Initial URL
http://www.nutt.net/2004/12/29/php-a-function-to-return-the-first-n-words-from-a-string/

Initial Description

                                

Initial Title
A PHP function to return the first N words from a string

Initial Tags
php

Initial Language
PHP