Skip to content

Instantly share code, notes, and snippets.

@tfevens
Created June 8, 2015 13:14
Show Gist options
  • Save tfevens/894050ff077bdd5c65a2 to your computer and use it in GitHub Desktop.
Save tfevens/894050ff077bdd5c65a2 to your computer and use it in GitHub Desktop.
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