Seonsoo Park
Seonsoo Park

Reputation: 31

regex find specific tables in html

i have html like bottom of this. and using PHP

<table style="...">
<tbody>
<tr> <img id="foo" src="foo"/></tr>
</tbody>
</table>
<p> ....</p>
<table style="...">
<tbody>
<tr> <img id="bar" src="bar"/></tr
</tbody>
</table>

I'm beginning PHP. I want to find specific table like img src or id equals foo or bar. but selected both tables. here is my regex 1.find tables has img tag

    /<table.*?>.*?<img *.*?<\/table>/

-> selected 2 table

2.add img src

<table.*?<img.+(src=.*?foo).*?<\/table>

-> selected all, from first tag to last tag

3.so try to not include </table> between ... tag.

<table.*?(?!<\/table>).*?<img.+(src=.*?foo).*?<\/table>

-> same result I don't know what is wrong! I was solved using preg_match_all() but still want know preg_match() has any idea??

thanks!

Upvotes: 0

Views: 158

Answers (1)

Nick
Nick

Reputation: 147206

This job is much better suited to using PHPs DOMDocument and DOMXPath classes. In this case we use an xpath to search for a table which has a descendant which is an img with it's src attribute equal to either 'foo' or 'bar':

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$footable = $xpath->query("//table[descendant::img[@src='foo']]");
echo $footable->item(0)->C14N() . "\n";
$bartable = $xpath->query("//table[descendant::img[@src='bar']]");
echo $bartable->item(0)->C14N() . "\n";

Output:

<table style="..."><tbody><tr><img id="foo" src="foo"></img></tr></tbody></table>
<table style="..."><tbody><tr><img id="bar" src="bar"></img></tr></tbody></table>

Demo on 3v4l.org

Upvotes: 2

Related Questions