php
1<?php
2$content = <<<EOT
3<img class="a" src="figure.jpg" />
4<img src="figure.jpg" class="a" />
5
6<img class="b" src="figure.jpg" />
7<img src="figure.jpg" class="b" />
8
9<img class="a b" src="figure.jpg" />
10<img src="figure.jpg" class="b c" />
11EOT;
12
13$pattern = '/<img[^/]*?class="[^"]*a[^"]*"[^/]*?/?>/';
14echo preg_replace($pattern, 'REPLACED', $content);
別解 (長い正規表現を使わない)
php
1<?php
2$content = <<<EOT
3<img class="a" src="figure.jpg" />
4<img src="figure.jpg" class="a" />
5
6<img class="b" src="figure.jpg" />
7<img src="figure.jpg" class="b" />
8
9<img class="a b" src="figure.jpg" />
10<img src="figure.jpg" class="b c" />
11EOT;
12
13// すべての <img> 要素を取得する
14preg_match_all('/<img.+?/?>/', $content, $matches, PREG_PATTERN_ORDER);
15
16$subjects = [];
17foreach($matches[0] as $match) {
18 $prefix_removed = explode('class="', $match)[1]; // 'a" src="figure.jpg" />' だけ残る
19 $suffix_removed = explode('"', $prefix_removed)[0]; // 'a' だけ残る
20 $classes = preg_split('/\s/', $suffix_removed); // ['a', 'b']
21
22 // 'a'クラスが含まれていない場合は弾く
23 if(!in_array('a', $classes, true)) continue;
24
25 $subjects[] = $match;
26}
27echo str_replace($subjects, 'REPLACED', $content);