首页 > 解决方案 > 使用 PHP 将 HTML 文档拆分为单词和跨度

问题描述

使用 PHP 我想将 HTML 文档拆分为单个单词,但将某些<span>s 放在一起。这与我到目前为止所获得的一样接近,只有一个 HTML 的最小示例(实际上会更大更复杂):

$html = '<html><body>

<h1>My header</h1>

<p>A test <b>paragraph</b> with <span itemscope itemtype="http://schema.org/Person">Bob Ferris</span> a person.</p>

</body></html>';

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);

foreach($xpath->query('.//span[@itemtype]|.//text()[normalize-space()]') as $node) {
    echo $node->nodeType . " " . $node->nodeValue . "<br>";
}

这输出:

3 我的标题
3 A 测试
3 第
3段
1 Bob Ferris
3 Bob Ferris
3 一个人。

nodeType3是文本节点,1是元素)

我还需要:

标签: phpxpath

解决方案


这似乎做到了:

// 1: Match all <span>s with an itemtype attribute.
// 2: OR
// 3: Match text strings that are not in one of those spans (and get rid of some spaces).
foreach($xpath->query('.//span[@itemtype]|.//text()[not(parent::span[@itemtype])][normalize-space()]') as $node) {
    if ($node->nodeType == 1) {
        // A span.
        echo $node->nodeValue . "<br>";
    } else {
        // A text node - split into words and trim trailing periods.
        $words = explode(" ", trim($node->nodeValue));
        foreach($words as $word) {
            echo rtrim($word, ".") . "<br>";
        }
    }
}

推荐阅读