Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I truncate a string to the first 20 words in PHP?

Tags:

string

php

How can I truncate a string after 20 words in PHP?

like image 345
sanders Avatar asked Jun 08 '09 14:06

sanders


People also ask

How do I limit 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.

How do I shorten text in PHP?

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)

How do I slice a string in PHP?

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.

How do you split the first 5 characters of a string?

You can use the substr function like this: echo substr($myStr, 0, 5);


2 Answers

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 ... 
like image 117
karim79 Avatar answered Sep 28 '22 12:09

karim79


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(""));  # => "" 
like image 20
nonopolarity Avatar answered Sep 28 '22 12:09

nonopolarity