Xpath 选择没有子节点的节点 [英] Xpath to Select nodes without its childrens
问题描述
我有一个网页,我想通过代码修改它(在特定单词上添加链接).
HTML 代码:
<h2>Notre histoire</h2><p style="text-align: justify;">SPECIFICS WORDS<strong>1998 : la création</strong></p><p style="text-align: justify;">pour objectif « de promouvoir, selon une démarche d'éducation active, auprès des jeunes et à travers eux, des projets d'expression集体和团结行动»(第 2 条).<br><br><strong>1999-2001 : les 首次亮相 SPECIFICS WORDS</strong></p><p style="text-align: justify;">SPECIFICS WORDS<a href="#">SPECIFICS WORDS</a></p>
所以我的目标是对特定单词进行 preg_replace,但仅限于那些在 P 中,但从 A 或 STRONG 或任何任一标签中取出的词.
我不能使用任何类或任何 id,因为我以前不知道代码!我尝试了 preg_replace PHP 函数,但它不起作用,而且执行时间太长.
所以我的问题是:如何使用 XPATh 选择一个没有 A、STRONG、IMG 子节点的节点?
不能选择没有子节点的节点.节点是树的子部分,除非它是叶子,在这种情况下它没有其他子节点.要选择包含单词SPECIFIC"的 TextNode 叶子,它们是 P 元素的直接子元素,您可以
//p/text()[contains(.,'SPECIFIC')]
这将排除其他元素内的文本节点,例如在强或a.
要替换它们,您可以
$dom = 新的 DOMDocument;$dom->loadHTML($html);$xpath = new DOMXPath($dom);foreach ($xpath->query('//p/text()[contains(.,"SPECIFIC")]') as $textNode) {$textNode->nodeValue = "REPLACED";}echo $dom->saveHTML();
另见php中的DOMDocument和这个
i've got a webpage that i would like to modify by code (adding link on specific words).
The HTML code:
<div class="section">
<h2>Notre histoire</h2>
<p style="text-align: justify;">SPECIFICS WORDS<strong>1998 : la création</strong></p>
<p style="text-align: justify;">pour objectif « de promouvoir, selon une démarche d’éducation active, auprès des jeunes et à travers eux, des projets d’expression collective et d’action de solidarité » (article 2).<br><br><strong>1999-2001 : les débuts SPECIFICS WORDS</strong></p>
<p style="text-align: justify;">SPECIFICS WORDS<a href="#">SPECIFICS WORDS</a></p>
</div>
So my aim is to preg_replace on SPECIFIC WORDS, but only those who are IN a P, but out from a A or a STRONG, or any either tags.
I can't use any class, or any id because i don't know the code before! I tried preg_replace PHP function, but it didn't work, and was too long to execute.
So my question is: How to select with XPATh a node without its A, STRONG, IMG chidrens ?
You cannot select nodes without their children. A node is a subpart of a tree, unless it is a leaf in which case it has not further children. To select the TextNode leaves containing the word "SPECIFIC" which are direct children of P elements, you do
//p/text()[contains(.,'SPECIFIC')]
This will exclude the text nodes inside other elements, e.g. in strong or a.
To replace them, you do
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//p/text()[contains(.,"SPECIFIC")]') as $textNode) {
$textNode->nodeValue = "REPLACED";
}
echo $dom->saveHTML();
Also see DOMDocument in php and this XPath Tutorial
这篇关于Xpath 选择没有子节点的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!