我有一个包含如下 html 标签的字符串。
$desc = "<p>Lorem <strong>ipsum</strong> dolor sit amet</p><p>Duo at agam maiorum instructior, ut tale quidam ancillae qui, est cu paulo consetetur.</p>"
我想取前 10 个字符:
- HTML 标签不计入。
- 所有打开的 HTML 标签都正确关闭。
现在如果使用 substr:
$result = substr($desc, 0, 10);
实际结果是:<p>Lorem <
我想要的是:<p>Lorem <strong>ipsu</strong></p>
最佳答案
我通过使用此处的非常好的代码实现了这一点 How to close unclosed HTML Tags?由 kamal 回答
<?php
$str = "<p>Lorem <strong>ipsum</strong> dolor sit amet</p><p>Duo at agam maiorum instructior, ut tale quidam ancillae qui, est cu paulo consetetur.</p>";
$s = strip_tags($str);
$result = substr($s, 0, 10);
$sarr = explode(' ', $result);
$last = end($sarr);
$l = strpos($str, $last);
$r = substr($str, 0, $l);
echo closetags($r.$last);
function closetags ( $html )
{
#put all opened tags into an array
preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result );
$openedtags = $result[1];
#put all closed tags into an array
preg_match_all ( "#</([a-z]+)>#iU", $html, $result );
$closedtags = $result[1];
$len_opened = count ( $openedtags );
# all tags are closed
if( count ( $closedtags ) == $len_opened )
{
return $html;
}
$openedtags = array_reverse ( $openedtags );
# close tags
for( $i = 0; $i < $len_opened; $i++ )
{
if ( !in_array ( $openedtags[$i], $closedtags ) )
{
$html .= "</" . $openedtags[$i] . ">";
}
else
{
unset ( $closedtags[array_search ( $openedtags[$i], $closedtags)] );
}
}
return $html;
}
?>
关于php - 如何在不干扰 HTML 标签的情况下从 php 字符串中剥离字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31675288/