php 保留html标签,PHP substr但保留HTML标签?

几个mounths之前我创建了一个特殊功能,它可以解决您的问题。

这是一个功能:

function substr_close_tags($code, $limit = 300)

{

if ( strlen($code) <= $limit )

{

return $code;

}

$html = substr($code, 0, $limit);

preg_match_all ( "#

foreach($result[1] AS $key => $value)

{

if ( strtolower($value) == 'br' )

{

unset($result[1][$key]);

}

}

$openedtags = $result[1];

preg_match_all ( "#([a-zA-Z]+)>#iU", $html, $result );

$closedtags = $result[1];

foreach($closedtags AS $key => $value)

{

if ( ($k = array_search($value, $openedtags)) === FALSE )

{

continue;

}

else

{

unset($openedtags[$k]);

}

}

if ( empty($openedtags) )

{

if ( strpos($code, ' ', $limit) == $limit )

{

return $html."...";

}

else

{

return substr($code, 0, strpos($code, ' ', $limit))."...";

}

}

$position = 0;

$close_tag = '';

foreach($openedtags AS $key => $value)

{

$p = strpos($code, (''.$value.'>'), $limit);

if ( $p === FALSE )

{

$code .= (''.$value.'>');

}

else if ( $p > $position )

{

$close_tag = ''.$value.'>';

$position = $p;

}

}

if ( $position == 0 )

{

return $code;

}

return substr($code, 0, $position).$close_tag."...";

}这是DEMO:http://sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201(单击“执行代码”以检查其工作原理)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值