PHP 正则表达式匹配 class 命名多个元素

PHP regex match by class name multiple elements

我有以下 HTML 和许多 class:

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

我正在使用 preg_match_all 查找所有图像

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

是否可以匹配具有 class 名称 red 的所有 img 标签?

我试过/red\d+/但没用

试试这个正则表达式:

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

演示:https://regex101.com/r/vLbXIJ/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);
?>

这里是ref