JBZoo\Utils\Str::limitWords PHP Method

limitWords() public static method

Truncate the string to given length of words.
public static limitWords ( string $string, integer $limit = 100, string $append = '...' ) : string
$string string
$limit integer
$append string
return string
    public static function limitWords($string, $limit = 100, $append = '...')
    {
        preg_match('/^\\s*+(?:\\S++\\s*+){1,' . $limit . '}/u', $string, $matches);
        if (!Arr::key(0, $matches) || self::len($string) === self::len($matches[0])) {
            return $string;
        }
        return rtrim($matches[0]) . $append;
    }

Usage Example

Ejemplo n.º 1
0
 public function testLimitWords()
 {
     is('The quick brown...', Str::limitWords('The quick brown fox jumps over the lazy dog', 3));
     is('The quick brown fox jumps...', Str::limitWords('The quick brown fox jumps over the lazy dog', 5));
     is('The...', Str::limitWords('The quick brown fox jumps over the lazy dog', 1));
     is('The quick brown fox jumps over the lazy dog', Str::limitWords('The quick brown fox jumps over the lazy dog', 90));
     is('The quick brown fox jumps over the...', Str::limitWords('The quick brown fox jumps over the lazy dog', 7));
 }