php - 使用 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 一个人。
(nodeType
3是文本节点,1是元素)
我还需要:
- 将文本节点拆分为单个单词并去除标点符号(在此阶段很容易完成,但可以在 xpath 查询中完成吗?)
- 仅捕获“Bob Ferris”元素,而不捕获“Bob Ferris”文本节点。
- 我也需要访问这些
<span>
s的属性$node->getAttribute()
解决方案
这似乎做到了:
// 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>";
}
}
}
推荐阅读
- apache-nifi - Nifi 处理器根据可变的正则表达式列表路由流
- javascript - 谷歌地图地理编码意外的财产位置
- laravel - 在控制器中一次引用所有模型?
- java - 在java jsp中包含文件(svg)
- c++ - Omnet++4.6 警告:不推荐使用“cLinkedList”
- c# - websocket握手期间的asp.net核心信号器错误
- ios - 点击单元格时如何执行到新 ViewController 的过渡动画
- go - 如何处理结构类型中的零结构变量
- python-3.x - Ping 操作在 pycharm 中运行良好,但在 jupyter notebook 中无法运行
- vue.js - 为什么单击按钮时不触发 Vue.js @input 事件?