How to truncate HTML with special characters?

谁都会走 提交于 2019-12-13 04:39:57

问题


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 and whatnot. My issue, though, is if the string includes special characters such as – or &

I need to truncate a string to 100 characters (or a few less if it would otherwise truncate in the middle of a special character). Right now I have a function:

$result= truncateIfNecessary(strip_tags($fullText), 100); //ignore HTML tags 

function truncateIfNecessary($string, $length) {
    if(strlen($string) > $length) {
        return substr($string, 0, $length).'...';
    } else {
        return $string;
    }
}

But if the string is something like text text – text (displayed on the page as: text text - text and $length falls in –, it returns text text &nda... which displays exactly like that, when I would need it to return text text....

EDIT:

(posted as answer)


回答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.




回答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



回答3:


I tried

function truncateIfNecessary($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:

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



回答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;
}


来源:https://stackoverflow.com/questions/18834329/how-to-truncate-html-with-special-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!