将特定的HTML标记分组为多个部分

时间:2014-01-27 19:26:47

标签: php html regex xml-parsing

我有一个带有这样标记的字符串:

<h3></h3>
<p><span><strong></strong></span></p>
<p></p>
<div></div>
<p></p>
<p></p>
<img />
<div></div>

我想将所有标记分组。但除了 div和imgs。这两个标签应该在它们自己的部分中,不应该组合在一起。所以结果应该是这样的:

<section>
    <h3></h3>
    <p><span><strong></strong></span></p>
    <p></p>
</section>

<section>
    <div></div>
</section>

<section>
    <p></p>
    <p></p>
</section>

<section>
    <img />
</section>

<section>
    <div></div>
</section>

我怎么能用php做到这一点?

1 个答案:

答案 0 :(得分:2)

假设您提供的内容仅在正文中,您可以使用:

$data = <<<'LOD'
<h3></h3>
<p><span><strong></strong></span></p>
<p></p>
<div></div>
<p></p>
<p></p>
<img />
<div></div>
<p><p><img /></p></p>
<!-- <img /> -->
<div> <div> </div> </div>
LOD;

$pattern = <<<'LOD'
~
(?(DEFINE)
    (?<comment> <!-- .*? --> )
    (?<cdata> \Q<![CDATA[\E .*? ]]> )
    (?<script_style> <s(cript|tyle)\b .*? </s\g{-1}> )
    (?<skip_list>
        \g<comment> | \g<cdata> | \g<script_style> 
    )

    (?<tag>
        <code\b .*? </code> | \g<self_closing_tag> |
        <(\w++) [^>]*+>
        (?> [^<]++ | \g<skip_list> | \g<tag> )*+
        </\g{-1}> 
    )
    (?<self_closing_tag> <(?:img|[bh]r)\b [^>]*+> )
    (?<other_tag> (?!<(?:img|div)\b) \g<tag>  )

    (?<div> (?=<div\b) \g<tag>)
    (?<img> (?=<img\b) \g<self_closing_tag>)

    (?<other_tags> \g<other_tag> (?>[^<]*+ \g<other_tag>)*+ )
)

\g<skip_list> (*SKIP)(*FAIL)
|
\g<div> | \g<img> | \g<other_tags>  

~xsi
LOD;


$result = preg_replace($pattern, "\n<section>\n$0\n</section>", $data);

echo htmlspecialchars($result);