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


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function shorten_string($string, $wordsreturned)
  2. /* Returns the first $wordsreturned out of $string. If string
  3. contains more words than $wordsreturned, the entire string
  4. is returned.*/
  5. {
  6. $retval = $string; // Just in case of a problem
  7. $array = explode(" ", $string);
  8. /* Already short enough, return the whole thing*/
  9. if (count($array)<=$wordsreturned)
  10. {
  11. $retval = $string;
  12. }
  13. /* Need to chop of some words*/
  14. else
  15. {
  16. array_splice($array, $wordsreturned);
  17. $retval = implode(" ", $array)." ...";
  18. }
  19. return $retval;
  20. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.