Posted By

Wardy on 09/18/08


Tagged

php String break word word-wrap


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

xmartyxcorex


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


 / Published in: PHP
 

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

  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. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: yurikolovsky on October 16, 2008

nice, the only snippet that works as it should! thanx!

note: you should consider changing the title to "A PHP FUNCTION TO SELECT THE FIRST WORDS FROM A STRING"

You need to login to post a comment.