Reputation: 3614
I need simple regex expression correctnes..
this regex
preg_replace('/(<img.*? class=".*?)(".*?>)/', '$1 ' . 'myclass' . '$2', $html)
targets this
<img src="er" alt="aa" width="641" height="481" class="class1 class2">
and works ok!
But wordpress generetes ending tag like this /> and regex failes
<img src="er" alt="aa" width="641" height="481" class="class1 class2" />
How to correct the regex?
Upvotes: 0
Views: 51
Reputation: 47874
Use a legitimate DOM parser to modify your HTML document.
Isolate the img tags, get their current class cakes, append your new class, then set the extended value back to the img.
Code: (Demo)
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
foreach ($doc->getElementsByTagName('img') as $img) {
$img->setAttribute('class', $img->getAttribute('class') . " myclass");
}
echo $doc->saveHTML();
Upvotes: 0
Reputation: 7587
preg_replace('/(<img.*? class=".*?)(".*?\/>)/', '$1 ' . 'myclass' . '$2', $html);
Upvotes: 3