假设我有
<body>
<p>This is a paragraph</p>
<p>This is another paragraph, there are three paragraphs in this page</p>
<p>Lorem ipsum dolor sit amet. Just another paragraph. Ut enim ad minim veniam.</p>
</body>
我想找到与'paragraph'匹配的所有单词,并在匹配单词之前和之后用4个单词包围它。结果列表如下:
我是xpath的新手,所以我能做的最好的是这段代码,它将获得包含'paragraph'的所有文本节点
$test = $xml->xpath('//body//*[text()[contains(.,"paragraph")]]');
所得:
提前致谢。
答案 0 :(得分:2)
您提到PHP的事实表明您可能正在寻找XPath 1.0解决方案。
这里有几个问题:
XPath 1.0没有良好的文本处理功能,也不能 用用户定义的函数弥补它们
XPath(1.0或2.0)无法创建新节点,因此具有 难以返回结构化结果。
如果您坚持使用PHP,因此使用XPath 1.0,我想我会满足于将匹配的文本节点返回给PHP应用程序,然后在PHP中完成其余的处理。
替代方案是使用XSLT:在XSLT 1.0中,它仍然是一个挑战,但借助递归模板,它当然是可能的。