0

I am trying to display the URL of an Image after every image in the main content on Wordpress. To do this I am building a plugin.

If add the following code within my plugin I can display 2 of the same Image. as the code to display the image is stored in $1 below.

$content = preg_replace("/(<img([^>]*)>)/i",
    "<div class=\"image_wrap\">$1<div class=\"linkbox\">" .
    "$1</div></div>", $content );

In theory all I need to do is hack at the second instance of $1 in the above code to strip the image src. So below is the code I have tried and it using some substr and strpos functions but that doesn't seem to want to work for me.

$content = preg_replace("/(<img([^>]*)>)/i",
    "<div class=\"image_wrap\">$1<div class=\"linkbox\">" . 
     substr(substr("$1", strpos("$1","src=\"")+5), 0,strpos(substr("$1",strpos("$1","src=\"")+5),"\"")) .
</div></div>", $content );

Is there anything glaringly wrong with this?

Thanks

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Shane Jones
  • 885
  • 1
  • 9
  • 27
  • Yes there is, please see [Grabbing the href attribute of an A element](http://stackoverflow.com/q/3820666/367456). Also it's not a real question you ask. – hakre Mar 03 '12 at 18:01
  • If you tried to evaluate those string patching expressions after the match, then you should have used them in a `preg_replace_callback` function. As you wrote it now, it gets executed before the `"$1"` is present. – mario Mar 03 '12 at 18:08
  • @mario - cannot figure out the preg_replace_callback stuff. Do you have any relevant example code? – Shane Jones Mar 04 '12 at 08:09
  • Figured it, posting solution back on here shortly – Shane Jones Mar 04 '12 at 09:59

2 Answers2

0

There are examples for preg_replace_callback in the manual. It usually goes like this:

$content = preg_replace_callback(
      "/(<img([^>]*)>)/i",
      "cb_image_wrap",
      $content
);

function cb_image_wrap($match) {

    list($all, $img, $attr) = $match;

    return
       "<div class=\"image_wrap\">$img<div class=\"linkbox\">" . 
       substr(substr("$img", strpos("$img","src=\"")+5), 0,
       strpos(substr("$img",strpos("$img","src=\"")+5),"\"")) .
       "</div></div>";
}

Your string patching code seems needlessly complicated.

It might also appropriate to look into HEREDOC strings.

mario
  • 144,265
  • 20
  • 237
  • 291
0

Here is the solution that I eventually figured out thanks to Mario in the above comments

$content = preg_replace_callback(
        '/(<img([^>]*)>)/i',
        create_function(
            '$matches',
            'return CREDIT_HEAD . 
             "<div class=\"image_wrap\">$matches[0]<div class=\"linkbox\">" . 
                        substr(substr("$matches[0]", strpos("$matches[0]","src=\"")+5), 0,strpos(substr("$matches[0]", strpos("$matches[0]","src=\"")+5),"\"")) .
                    "</div></div>" . 
                    CREDIT_FOOT;'
        ),
        $content);
Shane Jones
  • 885
  • 1
  • 9
  • 27