Search code examples
wordpresspreg-replacepreg-match

How to add image link as hyperlink to all images in content using preg_replace?


I want to change the hyperlink of all images I post in content to image link. For now I can edit its link to anything using this

function add_image_responsive_class($content) {
   global $post;
   $pattern ="~<a .*?>\s*<img(.*?)class=\"(.*?)\"(.*?)>\s*</a>~i";
   $replacement = '<a href="$1"><img$1class="$2"$3></a>';
   $content = preg_replace($pattern, $replacement, $content);
   return $content;
}
add_filter('the_content', 'add_image_responsive_class');

But I cant copy image link to hyperlink.

For example:

Now I have this:

<a href="http://www.mywebsite.com/mypage"><img src="imagelink"></a>

I want to change this to:

<a href="imagelink"><img src="imagelink"></a>

Solution

  • Okay, so there are a few ways you can do this. I'll show you one easy way, but know that you can customize this down to a finer granularity. The process will be the same, though.

    Basically we're going to split up the string into chunks and save each chunk by putting a set of parenthesis around it. We can then interchange chunks as we please.

    Let's take your string and divide it up into different parts.

    <a href="http://www.mywebsite.com/mypage"><img src="imagelink"></a>
    |---1---||---------------2-------------||-----3----||---4---||--5-|
    

    Really what we want to do here is replace #2 with #4. So the order would be:

    #1 #4 #3 #4 #5
    

    This is pretty easy to achieve with preg_replace and here's how:

    $link_text = '<a href="http://www.mywebsite.com/mypage"><img src="imagelink"></a>';
    
    // JUST ADD PARENTHESIS AROUND EACH ITEM YOU WANT TO CAPTURE
    $link_text = preg_replace('~(<a href=")(.*?)("><img src=")(.*?)("></a>)~i', '$1$4$3$4$5', $link_text);
    
    print $link_text;
    

    That give you the following:

    <a href="imagelink"><img src="imagelink"></a>
    

    That being said, you can really divide the string up however you wish ... doesn't have to be how I did it. The concept would be the same. Each set of parenthesis captures one item and gives it a number. You can then plug in that number into any other part of the string.

    Here is a working demo:

    http://ideone.com/49NH6V