这个字符串在 HTML 中有 78 个字符,在没有 HTML 中有 39 个字符:
<p>I really like the <a href="http://google.com">Google</a> search engine.</p>
我想根据非 HTML 字符数截断这个字符串,例如,如果我想将上面的字符串截断为 24 个字符,输出将是:
I really like the <a href="http://google.com">Google</a>
截断在确定要截断的字符数时没有考虑 html,它只考虑了剥离的计数。然而,它并没有留下开放的 HTML 标签。
最佳答案
好吧,这就是我放在一起的,它似乎在工作:
function truncate_html($string, $length, $postfix = '…', $isHtml = true) {
$string = trim($string);
$postfix = (strlen(strip_tags($string)) > $length) ? $postfix : '';
$i = 0;
$tags = []; // change to array() if php version < 5.4
if($isHtml) {
preg_match_all('/<[^>]+>([^<]*)/', $string, $tagMatches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach($tagMatches as $tagMatch) {
if ($tagMatch[0][1] - $i >= $length) {
break;
}
$tag = substr(strtok($tagMatch[0][0], " \t\n\r\0\x0B>"), 1);
if ($tag[0] != '/') {
$tags[] = $tag;
}
elseif (end($tags) == substr($tag, 1)) {
array_pop($tags);
}
$i += $tagMatch[1][1] - $tagMatch[0][1];
}
}
return substr($string, 0, $length = min(strlen($string), $length + $i)) . (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '') . $postfix;
}
用法:
truncate_html('<p>I really like the <a href="http://google.com">Google</a> search engine.</p>', 24);
该函数是从(做了一个小修改)抓取的:
关于php - 截断文本而不截断 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12268387/