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.
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.
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.
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.
$num_words = 101; $words = array(); $words = explode(" ", $original_string, $num_words); $shown_string = ""; if(count($words) == 101){ $words[100] = " ... "; } $shown_string = implode(" ", $words);
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