Search code examples
phpregeximagehtml-parsingclass-attributes

Add a new class to img tag's class list


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?


Solution

  • preg_replace('/(<img.*? class=".*?)(".*?\/>)/', '$1 ' . 'myclass' . '$2', $html);