PHP将一个html字符串分割成一个数组,类名tag作为键


PHP splitting a string of html into an array with class name of tag as key

我需要取一个html文本字符串,如:

<p>This is a line with no spans<br>
This is a line <span class="second">This is secondary</span><br>  
This is another line <span class="third">And this is third</span> <span class="four">this is four</span></p>

在PHP中以数组的形式出现,如

array(
    "This is a line with no spans",
    array(
      "This is a line",
      second => "This is secondary",
    ),
    array(
      "This is another line",
      third => "And this is third",
      four => "this is four"
    )
);

将每行设置为自己的值很容易,我只是用
这很好,但是将行与类名分开,我不能完全理解。我觉得php的preg_split可能是关键,但我对正则表达式有点糟糕,我不能弄清楚它。

任何想法?

您不应该尝试用正则表达式或其他方法解析HTML。它非常复杂,最终会出现可怕的维护问题。

我强烈建议你研究一下如何将一大块标记读入DOM文档[docs],然后使用DOM方法来处理它,就像你在浏览器端一样。

使用正则表达式解析HTML(引用)不是一个好主意。它不是一个合适的工具;请看@ jaulde的回答

最好的方法是完全使用DOM。循环遍历所有子节点(包括文本节点)以按所需方式格式化数组。这样的:

$p = // get paragraph tag...
$lines = array();
$pChildren = $p->childNodes;
for ($i = 0; $i < $pChildren->length; $i++) {
    $line = array();
    $child = $pChildren->item($i);
    if ($child instanceof DOMText) {
        $line[] = $child->wholeText;
    } elseif ($child instanceof DOMElement) {
        if (strtolower($child->tagName) == 'br') {
            $lines[] = $line;
            $line = array();
        } elseif (strtolower($child->tagName) == 'span' && $child->hasAttribute('class')) {
            $line[$child->getAttribute('class')] = $child->nodeValue;
        }
    }
}

警告:将上述代码视为伪代码,它根本没有经过测试,只是根据经验和手册。

也许您可以使用XML解析器?这是文档