Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse HTML with PHP DOM - Class contains text

I have a set of html items which are to be parsed. I need to parse the contents of a div whose class name ends with 'uid-g-uid'. Below are the sample divs...

<div class="uid-g-uid">1121</div>

<div class="yskisghuid-g-uid">14234</div>

<div class="kif893jduid-g-uid">114235</div>

I have tried the below combinations but didnt work

$doc = new DOMDocument();
$bdy = 'HTML Content goes here...';
@$doc->loadHTML($bdy);
$xpath = new DomXpath($doc);
$div = $xpath->query('//*[@class=ends-with(., "uid-g-uid")]');

and also tried

$doc = new DOMDocument();
$bdy = 'HTML Content goes here...';
@$doc->loadHTML($bdy);
$xpath = new DomXpath($doc);
$div = $xpath->query('//*[@class="*uid-g-uid"]');

Please help!

like image 244
Guns Avatar asked Jan 02 '26 08:01

Guns


1 Answers

ends-with() requires Xpath 2.0 so it won't work with DOMXPath which is Xpath 1.0. Something like this should work though:

$xpath->query('//*["uid-g-uid" = substring(@class, string-length(@class) - 8)]');
like image 66
Damien Legros Avatar answered Jan 03 '26 22:01

Damien Legros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!