PHP – Return 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:
-
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
-
/* Already short enough, return the whole thing
-
*/
-
{
-
$retval = $string;
-
}
-
else
-
/* Need to chop of some words
-
*/
-
{
-
}
-
return $retval;
-
}
Question, Comments...
Do you have more questions. Please either leave a comment below or join us in our new forum.