Skip to content Skip to sidebar Skip to footer

How To Truncate Html With Special Characters?

I'm aware of various ways to truncate an HTML string to a certain length including/not including the HTML tags as part of the result and/or truncating while preserving whole words

Solution 1:

I think your problem would be solved by changing the first line of code to:

$result = strip_tags(truncateIfNecessary($fullText, 100));

That way you first adjust the length and after that take care of the HTML characters.

Solution 2:

Use the wordwrap php function.

something like this:

$result= wordwrap(strip_tags($fullText), 100, "...\n"); // Remove HTML and split$result= explode("\n", $result);
$result=$result[0]; // Select the first group of 100 characters

Solution 3:

I tried

functiontruncateIfNecessary($string, $length) {
    if(strlen($string) > $length) {
        $string = html_entity_decode(strip_tags($string));
        $string = substr($string, 0, $length).'...';
        $string = htmlentities($string);
        return$string;
    } else {
        return strip_tags($string);
    }
}

but for some reason it missed a few – and •. For now, I found the solution at http://alanwhipple.com/2011/05/25/php-truncate-string-preserving-html-tags-words/ (linked at Shortening text tweet-like without cutting links inside) worked perfectly - handles htmltags, preserve whole words (or not), and htmlentities. Now it's just:

functiontruncateIfNecessary($string, $length) {
    if(strlen($string) > $length) {
        return truncateHtml($string, $length, "...", true, true);
    } else {
        return strip_tags($string);
    }
}

Solution 4:

function _truncate($string,$lenMax = 100) {

    $len = strlen($string);
    if ($len > $lenMax - 1) {
        $string = substr(strip_tags($string),0,$lenMax);
        $string = substr($string,0,strrpos($string," ")).'...';
    }

    return $string;
}

Post a Comment for "How To Truncate Html With Special Characters?"