ak47suk1

PHP: A function to return the first n words from a string

Dec 27th, 2011
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function shorten_string($string, $wordsreturned)
  2. /*  Returns the first $wordsreturned out of $string.  If string
  3. contains fewer words than $wordsreturned, the entire string
  4. is returned.
  5. */
  6. {
  7. $retval = $string;      //  Just in case of a problem
  8.  
  9. $array = explode(" ", $string);
  10. if (count($array)<=$wordsreturned)
  11. /*  Already short enough, return the whole thing
  12. */
  13. {
  14. $retval = $string;
  15. }
  16. else
  17. /*  Need to chop of some words
  18. */
  19. {
  20. array_splice($array, $wordsreturned);
  21. $retval = implode(" ", $array)." ...";
  22. }
  23. return $retval;
  24. //Source: http://www.nutt.net/2004/12/29/php-a-function-to-return-the-first-n-words-from-a-string/
  25. }
RAW Paste Data