Skip to content

Instantly share code, notes, and snippets.

@jcamp
Created July 25, 2018 14:41
Show Gist options
  • Save jcamp/14b06515de6f29d9a7971225073c4136 to your computer and use it in GitHub Desktop.
Save jcamp/14b06515de6f29d9a7971225073c4136 to your computer and use it in GitHub Desktop.
PHP function - Truncate string to a number of words and add elipse for read more...
<?php
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
// Limit to 5 words then pop in a '...'
echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment