Skip to content

Instantly share code, notes, and snippets.

@pein0119 pein0119/Words Limit forked from tfevens/Words Limit
Last active Aug 29, 2015

Embed
What would you like to do?
function words($value, $words = 100, $end = '...')
{
preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
if ( ! isset($matches[0]) || strlen($value) === strlen($matches[0])) return $value;
return rtrim($matches[0]).$end;
}
/*
Usage:
$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sem nunc, sodales eleifend magna sed, vestibulum pharetra quam. Aenean interdum consectetur sagittis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed egestas efficitur neque vitae pulvinar. Phasellus blandit neque et rutrum malesuada. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed tincidunt, erat ut sollicitudin dignissim, lectus odio bibendum est, at elementum nisi sem eu tellus. Aenean et sagittis ant.'
echo words($string,10); // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sem...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.