Filter the contents of a specific tag from a PHP variable?

I have the following value in the $ img_info variable ...

<p><img src="images/a.jpg" alt="" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eu ullamcorper felis.</p> 

How to filter or extract specific img tag content from only $img_info Variable? Is there any function available in PHP without using explode() ? ...

Please help me...

+4
source share
2 answers

You can use DOMDocument for this:

 $dom = new DOMDocument; $dom->loadHTML($img_info); echo $dom->saveXML($dom->getElementsByTagName('img')->item(0)); 

Output:

 <img src="images/a.jpg" alt="" /> 
+3
source

Yes there is preg_match ()

 $img_info = '<p><img src="images/a.jpg" alt="" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eu ullamcorper felis.</p>'; preg_match('/\<img\s+(?:.*?)\/\>/i', $img_info, $rgMatches); var_dump($rgMatches[0]); 

such problems are usually solved with regular expressions, so knowing them will be very useful

+1
source

Source: https://habr.com/ru/post/1498544/


All Articles