Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit text length in php and provide 'Read more' link

Tags:

text

php

I have text stored in the php variable $text. This text can be 100 or 1000 or 10000 words. As currently implemented, my page extends based on the text, but if the text is too long the page looks ugly.

I want to get the length of the text and limit the number of characters to maybe 500, and if the text exceeds this limit I want to provide a link saying, "Read more." If the "Read More" link is clicked, it will show a pop with all the text in $text.

like image 388
Scorpion King Avatar asked Nov 23 '10 16:11

Scorpion King


People also ask

How do I limit text length in PHP?

Approach 2 (Using mb_strimwidth() function): The mb_strimwidth function is used to get truncated string with specified width. It takes as input the string and the required number of characters.

How do I create a Read More link from a string in PHP?

So here you can do it using php substr(). PHP substr() through we will get specific character from string and return with read more link. In this example i make single function to display read more link after some character, you can pass specific character like 100, 200, 500, 1000 etc.


2 Answers

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.     $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);     $string .= '... <a href="/this/story">Read More</a>'; } echo $string; 

You can tweak it further but it gets the job done in production.

like image 126
webbiedave Avatar answered Oct 11 '22 13:10

webbiedave


$num_words = 101; $words = array(); $words = explode(" ", $original_string, $num_words); $shown_string = "";  if(count($words) == 101){    $words[100] = " ... "; }  $shown_string = implode(" ", $words); 
like image 30
Brian H Avatar answered Oct 11 '22 15:10

Brian H