How can I truncate a string after 20 words in PHP?
This is what I use: // strip tags to avoid breaking any html $string = strip_tags($string); if (strlen($string) > 500) { // truncate string $stringCut = substr($string, 0, 500); $endPoint = strrpos($stringCut, ' '); //if the string doesn't contain any space then it will cut without word basis.
You can specify the following variables: $text – The text string that you want to shorten. $max – The maximum number of characters allowed (default = 50) $append – The appended text (default = ellipses)
The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.
You can use the substr function like this: echo substr($myStr, 0, 5);
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; } echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
Outputs:
Hello here is a long ...
Change the number 3
to the number 20
below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3
to 20
to change the default value):
function first3words($s, $limit=3) { return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s); } var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world" var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world" var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world" var_dump(first3words("hello yes world")); # => "hello yes world" var_dump(first3words("hello yes world.")); # => "hello yes world" var_dump(first3words("hello yes")); # => "hello yes" var_dump(first3words("hello")); # => "hello" var_dump(first3words("a")); # => "a" var_dump(first3words("")); # => ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With