Created
July 25, 2018 14:41
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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