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

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

if(count($words) == 101){
   $words[100] = " ... ";
}

$shown_string = implode(" ", $words);

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.


I have combine two different answers:

  1. Limit the characters
  2. Complete HTML missing tags

    $string = strip_tags($strHTML);
    $yourText = $strHTML;
    if (strlen($string) > 350) {
        $stringCut = substr($post->body, 0, 350);
        $doc = new DOMDocument();
        $doc->loadHTML($stringCut);
        $yourText = $doc->saveHTML();
    }
    $yourText."...<a href=''>View More</a>"
    

There is an appropriate PHP function: substr_replace($text, $replacement, $start).

For your case, because you already know all the possibilities of the text length (100, 1000 or 10000 words), you can simply use that PHP function like this:

echo substr_replace($your_text, "...", 20);

PHP will automatically return a 20 character only text with ....

Se the documentation by clicking here.

Tags:

Php

Text