SPQRInc
SPQRInc

Reputation: 188

Use DOMXPath to exclude an array of tags

I am using:

$dom = new \DOMDocument();
$xpath = new \DOMXPath( $dom );

to modify the DOM of my page.

I can exclude all elements that have an a tag using:

$xpath->query( '//text()[not(ancestor::a)]' )

I would like to exclude a dynamic array of tags like:

$array => ['a', 'img', 'code'];

Is there a handy way to bundle these conditions?

Upvotes: 0

Views: 70

Answers (1)

Mitya
Mitya

Reputation: 34556

It's just a question of iterative string building. Actually you can automate the iteration by using implode() for simple, indexed, flat arrays like yours:

$array => ['a', 'img', 'code'];
$xpath->query( '//text()[ not(ancestor::'.implode(') and not(ancestor::', $array).']'))

Should produce:

$xpath->query( '//text()[not(ancestor::a) and not(ancestor::img) and not(ancestor::code)]')

Upvotes: 1

Related Questions