I am attempting to search all images , grab a cssclass which begins with "align" and move the class to a new attribute. I'm not sure whether my regex is wrong or if its my preg_replace_callback script
function set_image_attribute_from_class($content){
// need to look only at the images, pref only those with class beginning "align"
// ex: <img class="alignleft class2" /> or <img class="alignright class3 class4" />
$search = "/(<img\b src=)"([^"]+)"(.* class=".*align(?:.|[^"]*)"[^>]+>)/";
$html = preg_replace_callback($search, 'my_replace_callback', $content);
return $html
}
function my_replace_callback($match) {
preg_match_all('#align(.*?)(\b)#si', $match, $arr, PREG_PATTERN_ORDER);
$eachImagePartialCssClassName = $arr[1][0]; //the css after the word "align"
return {{{original image with classes intact}}} . 'align='. $eachImagePartialCssClassName .'/>'{{{close the image tag}}}'
}
START WITH:
$content
Search for
<p>I am copy here just for fun but please dont remove me</p>
<img src="xxx" class="alignleft class2" alt="xxx" />
<img src="xxx" class="alignright class3 class4" />
<p>more copy but please dont remove me</p>
<img src="xxx" class="alignnone class93 class11" title="xxx" />
<img src="xxx" class="class2" alt="xxx" />
End up with
<p>I am copy here just for fun but please dont remove me</p>
<img src="xxx" class="alignleft class2" alt="xxx" ALIGN="LEFT" />
<img src="xxx" class="alignright class3 class4" ALIGN="RIGHT" />
<p>more copy but please dont remove me</p>
<img src="xxx" class="alignnone class93 class11" title="xxx" ALIGN="NONE" />
<img src="xxx" class="class2" alt="xxx" /> {{{this one didn't have anything to change}}}
The rest of the stuff inside the image tags and the rest of the text / content I want to keep intact - - ex: copy remains, srcs unchanged, alt tags, title tags etc stay.
Final note - I know people are big on DomDocument etc. or jQuery. Could you please help me out with a regular php, regex verion. Not DomDocument?