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

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

+50
string php
Jun 08 '09 at 14:45
source share
21 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 blah blah blah blah blah hahahaha haha haaaaaa', 5); 

Outputs:

 Hello here is a long ... 
+105
Jun 08 '09 at 14:51
source share

change the number 2 to the number 19 below to get the first 20 words. The following demonstrates the use of 2 to get the first three words: (so change 2 to 19 and it will give you the first 20 words)

 function first3words($s) { return preg_replace('/((\w+\W*){2}(\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("")); # => "" 
+23
Jun 08 '09 at 15:07
source share

To the nearest space

Truncates to the nearest preceding space of the target character. Demo

  • $str String to be truncated
  • $chars number of characters to be deleted can be overridden $to_space
  • $to_space boolean in order to truncate from space around $chars limit

Function

 function truncateString($str, $chars, $to_space, $replacement="...") { if($chars > strlen($str)) return $str; $str = substr($str, 0, $chars); $space_pos = strrpos($str, " "); if($to_space && $space_pos >= 0) $str = substr($str, 0, strrpos($str, " ")); return($str . $replacement); } 

Example

 <?php $str = "this is a string that is just some text for you to test with"; print(truncateString($str, 20, false) . "\n"); print(truncateString($str, 22, false) . "\n"); print(truncateString($str, 24, true) . "\n"); print(truncateString($str, 26, true, " :)") . "\n"); print(truncateString($str, 28, true, "--") . "\n"); ?> 

Exit

 this is a string tha... this is a string that ... this is a string that... this is a string that is :) this is a string that is-- 
+9
Apr 10 2018-12-12T00:
source share

A simple and fully equipped truncate () method:

 function truncate($string, $width, $etc = ' ..') { $wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2); return $wrapped[0] . (isset($wrapped[1]) ? $etc : ''); } 
+6
Mar 01 '14 at 15:04
source share

use explode () .

An example from the documents.

 // Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 

Note that the explode function has a restriction function. So you can do something like

 $message = implode(" ", explode(" ", $long_message, 20)); 
+5
Jun 08 '09 at 14:56
source share

This is not my own creation, its modification of previous posts. loans go to karim79.

 function limit_text($text, $limit) { $strings = $text; if (strlen($text) > $limit) { $words = str_word_count($text, 2); $pos = array_keys($words); if(sizeof($pos) >$limit) { $text = substr($text, 0, $pos[$limit]) . '...'; } return $text; } return $text; } 
+5
Jan 24 '12 at 6:18
source share

Divide the string (into an array) by < space > , and then take the first 20 elements of this array.

+4
Jun 08 '09 at 14:49
source share

This looks pretty good to me :

A common problem when creating dynamic web pages (where the content is obtained from a database, system content management or an external source such as an RSS feed) is that the input text may be too long and cause the page to break.

One solution is to truncate the text so that it fits on the page. This sounds simple, but often results are not expected because of words and sentences are inappropriate points.

+4
Jun 08 '09 at 14:50
source share

Try regex.

You need something that matches 20 words (or 20 word boundaries).

So (my regex is awful, so correct me if that is not accurate):

 /(\w+\b){20}/ 

And here are some examples of regex in php .

+4
Jun 08 '09 at 14:51
source share

With triple points:

 function limitWords($text, $limit) { $word_arr = explode(" ", $text); if (count($word_arr) > $limit) { $words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...'; return $words; } return $text; } 
+3
Aug 03 '14 at 1:35
source share

Something like this could probably do the trick:

 <?php $words = implode(' ', array_slice(split($input, ' ', 21), 0, 20)); 
+2
Jun 08 '09 at 14:51
source share

use PHP strtok () token function in a loop.

 $token = strtok($string, " "); // we assume that words are separated by sapce or tab $i = 0; $first20Words = ''; while ($token !== false && $i < 20) { $first20Words .= $token; $token = strtok(" "); $i++; } echo $first20Words; 
+2
Jun 08 '09 at 14:57
source share

based on 能量 answer:

 function truncate_words($string,$words=20) { return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string); } 

or

 function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') { $new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string); if($new != $string){ return $new.$ellipsis; }else{ return $string; } } 
+2
Sep 29 2018-11-11T00:
source share

Here is what I implemented.

 function summaryMode($text, $limit, $link) { if (str_word_count($text, 0) > $limit) { $numwords = str_word_count($text, 2); $pos = array_keys($numwords); $text = substr($text, 0, $pos[$limit]).'... <a href="'.$link.'">Read More</a>'; } return $text; } 

As you can see, it is based on the answer of karim79, all that needed to be changed was that the if statement should also check for words, not characters.

I also added a link to the main function for convenience. Until now, it has worked flawlessly. Thanks to the first solution provider.

+1
Sep 29 '11 at 9:31
source share

Here I use:

  $truncate = function( $str, $length ) { if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) { $str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length )); return htmlspecialchars($str[0]) . '&hellip;'; } else { return htmlspecialchars($str); } }; return $truncate( $myStr, 50 ); 
+1
Jan 10 '12 at 8:29
source share

Another solution :)

 $aContent = explode(' ', $cContent); $cContent = ''; $nCount = count($aContent); for($nI = 0; ($nI < 20 && $nI < $nCount); $nI++) { $cContent .= $aContent[$nI] . ' '; } trim($cContent, ' '); echo '<p>' . $cContent . '</p>'; 
+1
Oct 05
source share

This worked for UNICODE clauses (UTF8) :

 function myUTF8truncate($string, $width){ if (mb_str_word_count($string) > $width) { $string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string); } return $string; } 
+1
Jun 03 '15 at 9:10
source share
 function getShortString($string,$wordCount,$etc = true) { $expString = explode(' ',$string); $wordsInString = count($expString); if($wordsInString >= $wordCount ) { $shortText = ''; for($i=0; $i < $wordCount-1; $i++) { $shortText .= $expString[$i].' '; } return $etc ? $shortText.='...' : $shortText; } else return $string; } 
+1
Dec 19 '17 at 12:36 on
source share

Try entering the code,

  $text = implode(' ', array_slice(explode(' ', $text), 0, 32)) echo $text; 
0
Oct. 16 '17 at 7:10
source share

To limit the words, I use the following small code:

  $string = "hello world ! I love chocolate."; $explode = array_slice(explode(' ', $string), 0, 4); $implode = implode(" ",$explode); echo $implode; 

$ implot will give: hello world! I

0
Nov 25 '17 at 17:57
source share

What about

 chunk_split($str,20); 

Writing a PHP Manual

-one
Jun 08 '09 at 15:30
source share



All Articles