Word Limiter function that preserves the original whitespace

Wednesday, March 3, 2010 9:03
<?php

echo word_limiter('this is my text for t',3); // display 3 words

function word_limiter($str, $limit = 10, $end_char = '&#8230;') {

    if (trim($str) == '')
        return $str;

    preg_match('/\s*(?:\S*\s*){'. (int) $limit .'}/', $str, $matches);

    if (strlen($matches[0]) == strlen($str))
        $end_char = '';

    return rtrim($matches[0]) . $end_char;
}

?>
  • Share/Bookmark
You can leave a response, or trackback from your own site.

Leave a Reply