如何截断带有特殊字符的HTML? [英] How to truncate HTML with special characters?
问题描述
我知道各种方法将HTML字符串截短到一定的长度,包括/不包括HTML标签作为结果的一部分和/或截断,同时保留整个单词和什么。不过,我的问题是,如果字符串包含特殊字符,例如& ndash;
或& amp;
我需要将一个字符串截断为100个字符(如果在特殊字符中间会截断,则会少一些)。现在我有一个函数: 但是,如果字符串是类似于 编辑: (以答案形式发布) 我试过 但由于某种原因,它错过了几个 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 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: But if the string is something like EDIT: (posted as answer) I tried but for some reason it missed a few
这篇关于如何截断带有特殊字符的HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b $ pre $ $ result = truncateIfNecessary(strip_tags($ fullText),100); //忽略HTML标签
函数truncateIfNecessary($ string,$ length){
if(strlen($ string)> $ length){
return substr($ string, 0,$ length)。'...';
} else {
return $ string;
$ b 文本文本和ndash;文本
(在页面上显示为: text text - text
和 $ length
落入& ndash;
,它会返回 text text& nda ...
需要它返回文本文本...
。
< pre $ 函数truncateIfNecessary($ string,$ length){
if(strlen($ string)> $ length){
$ string = html_entity_decode(strip_tags($字符串));
$ string = substr($ string,0,$ length)。'...';
$ string = htmlentities($ string);
return $ string;
} else {
return strip_tags($ string);
}
}
& ndash;
和& bull;
。目前,我在 http://alanwhipple.com/2011/05/25/php-truncate-string-preserving-html-tags-words/ (链接在缩短文本推文,而不切断链接内)完美工作 - 处理htmltags,保留整个单词(或不),以及htmlentities。现在它只是:
$ b $ pre $ 函数truncateIfNecessary($ string,$ length){
if(strlen($ string)> ; $ length){
return truncateHtml($ string,$ length,...,true,true);
} else {
return strip_tags($ string);
}
}
–
or &
$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;
}
}
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...
.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);
}
}
–
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);
}
}