首页 > 解决方案 > 将html标签添加到PHP中的字符串

问题描述

我想将 html 标签添加到 PHP 中的 HTML 字符串中,例如:

<h2><b>Hello World</b></h2>
<p>First</p>
Second
<p>Third</p>

第二个没有被任何 html 元素包裹,所以系统会在其中添加 p 标签,预期结果:

<h2><b>Hello World</b></h2>
<p>First</p>
<p>Second</p>
<p>Third</p>

尝试使用 PHP Simple HTML DOM Parser 但不知道如何处理它,这是我的想法示例:

function htmlParser($html)
{
    foreach ($html->childNodes() as $node) {
        if ($node->childNodes()) {
            htmlParser($node);
        }
        // Ideally: add p tag to node innertext if it does not wrapped with any tag
    }

    return $html;
}

但是childNode不会循环进入Second,因为它里面没有包裹元素,并且不建议使用正则表达式来处理html标签,有什么想法吗?

非常感谢,谢谢。

标签: phpsimple-html-dom

解决方案


这是一个很酷的问题,因为它促进了对 DoM 的思考。

我提出了一个问题HTML Parsers 如何处理未标记的文本, @sideshowbarker对此进行了慷慨的评论,这让我思考,并提高了我对 DoM 的了解,尤其是关于文本节点的知识。

下面是一种基于 DoM 的查找候选文本节点并用“p”标签填充它们的方法。有很多文本节点我们应该不用管,比如我们用于格式化的空格、回车和换行(“丑陋”可能会去掉)。

<?php

$html = file_get_contents("nodeTest.html"); // read the test file
$dom = new domDocument;            // a new dom object
$dom->loadHTML($html);             // build the DoM
$bodyNodes = $dom->getElementsByTagName('body');  // returns DOMNodeList object
foreach($bodyNodes[0]->childNodes as $child)      // assuming 1 <body> node
{
    $text="";
    // this tests for an untagged text node that has more than non-formatting characters
    if ( ($child->nodeType == 3) && ( strlen( $text = trim($child->nodeValue)) > 0 ) )
    { // its a candidate for adding tags
        $newText = "<p>".$text."</p>";  
        echo str_replace($text,$newText,$child->nodeValue);
    }
    else
    {   // not a candidate for adding tags
        echo $dom->saveHTML($child);
    }
}     

nodeTest.html 包含这个。

<!DOCTYPE HTML> 
<html>
<body>
    <h2><b>Hello World</b></h2>
    <p>First</p>
    Second
    <p>Third</p>
    fourth
    <p>Third</p>
    <!-- comment -->
</body>
</html>

输出是这样的......我没有费心回显外部标签。请注意,注释和格式已正确处理。

<h2><b>Hello World</b></h2>
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>fourth</p>
<p>Third</p>
<!-- comment -->

显然,如果您希望使事物更通用,则需要遍历 DoM 并在每个元素节点处重复搜索/替换。在此示例中,我们仅在Body节点处停止并处理每个直接子节点。

我不是 100% 确定代码是最有效的,如果我找到更好的方法,我可能会对此进行更多思考并更新。


推荐阅读