Home > OS >  How to match HTML img tag with attributes
How to match HTML img tag with attributes

Time:03-26

This is what I got so far: https://regex101.com/r/YirMZ4/2 But it's not correct, because it will not match if I remove a certain attribute or place it in a different order.

<img\s align="(?:\.{2}\/)?(.*?)"\s height="(?:\.{2}\/)?(.*?)"\s src="(?:\.{2}\/)?(.*?)"\s style="(?:\.{2}\/)?(.*?)"\s width="(?:\.{2}\/)?(.*?)"\/?>

<img align="" height="400" src="../../assets/images/Quantum.png" style="vertical-align: middle; margin-right: auto; margin-left: auto;" width="131"/>

I am trying to match the HTML IMG tag with attributes, no matter, if a certain attribute is present or not, and attribute order, should not matter.

How can I do that?

CodePudding user response:

It is much easier with DOM:

$html = <<<'HTML'
<img 
  align="" 
  height="400" 
  src="../../assets/images/Quantum.png" 
  style="vertical-align: middle; margin-right: auto; margin-left: auto;" width="131"/>
HTML;

$document = new DOMDocument();
$document->loadHTML($html,  LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('//img') as $imageNode) {
    $src = $imageNode->getAttribute('src'); 
    $imageNode->setAttribute('src', 'http://example.com/path/app/'.$src);
}

echo $document->saveHTML();
  • Related