Posted By

Ngoc on 09/29/09


Tagged

trim cut word


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

silentbob84


Trim A String To A Given Word Count


 / Published in: PHP
 

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

Cut or trim a string by given word number

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

Report this snippet  

You need to login to post a comment.