字符串过长截断 html,截断包含HTML标记的字符串

一个功能怎么样?这是我的 - AbstractHTMLContents。它有两个参数:

输入HTML内容,

限制。

以下是代码:

function AbstractHTMLContents($html, $maxLength=100){

mb_internal_encoding("UTF-8");

$printedLength = 0;

$position = 0;

$tags = array();

$newContent = '';

$html = $content = preg_replace("/]+\>/i", "", $html);

while ($printedLength < $maxLength && preg_match('{?([a-z]+)[^>]*>|?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position))

{

list($tag, $tagPosition) = $match[0];

// Print text leading up to the tag.

$str = mb_strcut($html, $position, $tagPosition - $position);

if ($printedLength + mb_strlen($str) > $maxLength){

$newstr = mb_strcut($str, 0, $maxLength - $printedLength);

$newstr = preg_replace('~\s+\S+$~', '', $newstr);

$newContent .= $newstr;

$printedLength = $maxLength;

break;

}

$newContent .= $str;

$printedLength += mb_strlen($str);

if ($tag[0] == '&') {

// Handle the entity.

$newContent .= $tag;

$printedLength++;

} else {

// Handle the tag.

$tagName = $match[1][0];

if ($tag[1] == '/') {

// This is a closing tag.

$openingTag = array_pop($tags);

assert($openingTag == $tagName); // check that tags are properly nested.

$newContent .= $tag;

} else if ($tag[mb_strlen($tag) - 2] == '/'){

// Self-closing tag.

$newContent .= $tag;

} else {

// Opening tag.

$newContent .= $tag;

$tags[] = $tagName;

}

}

// Continue after the tag.

$position = $tagPosition + mb_strlen($tag);

}

// Print any remaining text.

if ($printedLength < $maxLength && $position < mb_strlen($html))

{

$newstr = mb_strcut($html, $position, $maxLength - $printedLength);

$newstr = preg_replace('~\s+\S+$~', '', $newstr);

$newContent .= $newstr;

}

// Close any open tags.

while (!empty($tags))

{

$newContent .= sprintf('%s>', array_pop($tags));

}

return $newContent;

}

看起来,它给出了你期望的结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值