LiliwoL
LiliwoL

Reputation: 43

Xpath to Select nodes without its childrens

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 ?

Upvotes: 4

Views: 1119

Answers (2)

O. R. Mapper
O. R. Mapper

Reputation: 20780

If I understand correctly, you want to select all nodes in the Xml document that are direct children of a <p> element, without any other elements in between. This is possible as follows:

`//p/node()[not(self::*)]`

This expression selects

  1. in all <p> elements
  2. the immediate child nodes (without any intermediate levels)
  3. unless they are elements.

Upvotes: 0

Gordon
Gordon

Reputation: 317197

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

Upvotes: 2

Related Questions