WordPress.org

Ready to get started?Download WordPress

Forums

Turning IMGs into divs with background-image (preg_replace) (3 posts)

  1. gorka.molero
    Member
    Posted 3 months ago #

    Hey guys!

    I'm trying something out but as I'm not versed in PHP it feels like smashing my head against random walls.

    I need to alter the output of image tags. I want to replace the img tag for a div with a background image, to achieve sort of this effect.

    I'm working around this function, in functions.php. This only takes the full image code and outputs it into the background-image url. I would need to extract the SRC.

    function turnItIntoDiv( $content ) {
    
       // A regular expression of what to look for.
       $pattern = '/(<img([^>]*)>)/i';
       // What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
       $replacement = '<div class="full-image" style="background-image: url("$1")"></div>';
    
       // run preg_replace() on the $content
       $content = preg_replace( $pattern, $replacement, $content );
    
       // return the processed content
       return $content;
    }
    
    add_filter( 'the_content', 'turnItIntoDiv' );

    Thank you all

  2. bcworkz
    Member
    Posted 3 months ago #

    Try using preg_replace_callback(). You will want to modify the matching regexp so that the match is broken up into 3 parts, img tag up to src=", the image url, and the rest of the tag.

    Your callback function then has the image URL ready to place into the background image style URL. This much can be accomplished with the regular preg_replace(). The only problem with your code now is you are capturing the entire img tag instead of just the URL. The regexp needs to be altered so it only captures the URL, so it must also match src=" and the closing " (or '), with parenthesis around only the intervening URL text. Use preg_replace_all() to handle all images if you don't like my callback idea.

    The reason I suggest the callback version is you could use extra code to locate larger versions of smaller images, which could greatly enhance how often the effect can be used effectively.

    I'm not that well versed in regexp, so I can't suggest a proper one. I can point you to a useful tool with which to test your regexp, sort of jsfiddle for regexp. As you've been warned of my lack of regexp skill, I'll take a guess at a regexp to start with: /<img.+src=['|"](.+)['|"].*>/i

  3. gorka.molero
    Member
    Posted 3 months ago #

    Excellent! Thank you sir, I'll post my final code in a bit

Reply

You must log in to post.

About this Topic