Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
I just noticed I said "search for" and included p tags etc. I don't want to search for p tags, nor images without that class beginning with align. Just want to make sure I don't overwrite the unaffected content thats already there – user925737 Mar 12 at 21:24

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.