Trim A String To A Given Word Count


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

Cut or trim a string by given word number


Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3. * Trim a string to a given number of words
  4. *
  5. * @param $string
  6. * the original string
  7. * @param $count
  8. * the word count
  9. * @param $ellipsis
  10. * TRUE to add "..."
  11. * or use a string to define other character
  12. * @param $node
  13. * provide the node and we'll set the $node->
  14. *
  15. * @return
  16. * trimmed string with ellipsis added if it was truncated
  17. */
  18. function word_trim($string, $count, $ellipsis = FALSE){
  19. $words = explode(' ', $string);
  20. if (count($words) > $count){
  21. array_splice($words, $count);
  22. $string = implode(' ', $words);
  23. if (is_string($ellipsis)){
  24. $string .= $ellipsis;
  25. }
  26. elseif ($ellipsis){
  27. $string .= '&hellip;';
  28. }
  29. }
  30. return $string;
  31. }
  32. ?>

URL: http://www.lullabot.com/articles/trim_a_string_to_a_given_word_count

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.