【问题标题】:Split HTML document into words and spans using PHP使用 PHP 将 HTML 文档拆分为单词和跨度
【发布时间】:2020-04-09 10:47:20
【问题描述】:

使用 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个测试
3段
3 与
1 鲍勃·费里斯
3 鲍勃·费里斯
3个人。

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

我还需要:

  • 将文本节点拆分为单个单词并去除标点符号(在此阶段很容易完成,但可以在 xpath 查询中完成吗?)
  • 仅捕获“Bob Ferris”元素,而不捕获“Bob Ferris”文本节点。
  • 我也需要使用$node-&gt;getAttribute() 访问这些&lt;span&gt;s 的属性

【问题讨论】:

  • 我猜不是.//text() 我想说“所有不在span[@itemtype] 内的文本节点”...?

标签: php xpath


【解决方案1】:

这似乎可以做到:

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

【讨论】:

    【解决方案2】:

    只是为了好玩,一个带有 XPath 2.0 的衬里:

    tokenize(replace(replace(concat(string-join((//text()[not(parent::span)][normalize-space()])[position()<last()]|//span[@itemtype],","),replace((//text()[not(parent::span)][normalize-space()])[last()],"\W$","")),"\W+",","),replace(//span[@itemtype]/text(),"\W+",","),//span[@itemtype]/text()),",+")
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2011-05-30
      相关资源
      最近更新 更多