PHP html-snippet中的关闭标签

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP html-snippet中的关闭标签相关的知识,希望对你有一定的参考价值。

<?php

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;
}

$str  = "<div>This is some interesting <strong><em>content!</em> And this</strong> line is <em>";
$str .= "abundantly</em> formatted</div>";

$snippet = substr ( $str, 0, 45 );

$snippet = strrpos ( $snippet, "<" ) > strrpos ( $snippet, ">" ) ? rtrim ( substr ( $str, 0, strrpos ( $snippet, "<" ) ) ) . "....." : rtrim ( $snippet ) . ".....";

$x = closetags ( $snippet );

print htmlspecialchars ( $x );

?>

以上是关于PHP html-snippet中的关闭标签的主要内容,如果未能解决你的问题,请参考以下文章

用数据库中的值填充select标签[关闭]

php中的短标签 太坑人了

PHP 关闭未关闭的标签

单击html中的提交并运行php代码[关闭]

从 Instagram 获取所有带有 PHP 特定标签的照片 [关闭]

php 关闭所有xhtml标签