0

I have the following HTML with many classes:

<img class="lorem ipsum red" />
<img class="red" />
<img class="lorem red ipsum dolor" />
<img class="red ipsum" />

I'm using preg_match_all to find all images

preg_match_all( '/<img [^>]+>/', $html, $matches )

Is it possible to match all img tags which have class name red?

I tried /red\d+/ but does not work

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215
  • You can refer to this [link](https://stackoverflow.com/questions/6651303/regex-match-img-tag-with-certain-attribute-class) – Rahul Feb 22 '19 at 11:54

2 Answers2

1

Try with this regex:

/<img.+?class=".*?red.*?"/

Demo: https://regex101.com/r/vLbXIJ/1

José Antonio Postigo
  • 2,674
  • 24
  • 17
1

Using regex to find HTML elements (of this complexity): Bad idea. Use an HTML parser and XPath! Even in JavaScript you can leverage DOM.

?php 
$doc =<<<DEMO
<img class="lorem ipsum red" />
<img class="red" />
<img class="lorem red ipsum dolor" />
<img class="red ipsum" />
DEMO;

$xml = new DOMDocument();
//Or you could use for locally saved files
//@$xml->loadHTMLFile('savedfile.html');
@$xml->loadHTML($doc);
foreach($xml->getElementsByTagName('img') as $image) {
    if(strstr($image->getAttribute('class'),'red')==true){
        $images[] = $image->getAttribute('src');
    }
}
print_r($images);
?>

Here is ref.

Rahul
  • 18,271
  • 7
  • 41
  • 60