Turning IMGs into divs with background-image (preg_replace)

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.

Read More

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 in advance

Related posts

Leave a Reply

1 comment

  1. Maybe it would by fine to split.

    if (preg_match("/img/i",$content))
    {
        ..
        $pattern = '/src="([^"]+)"/i';   
        ..
    

    Then you will get exact file name. Height of div should be set.

    Whole code – matching all images:

    if (preg_match("/img/i",$content))
    {
      if (preg_match_all('/src[ ]?=[ ]?"([^"]+)"/i',$content,$matches))
      { 
        foreach ($matches[1] as $i => $match)
        {
           $replacement = '<div class="full-image" style="background-image: url('' . trim($match) . '')"></div>';
    
            $content = preg_replace("~(<img(.*){$matches[0][$i]}[^>]+>)~i",$replacement,$content);
         }
      }
    }
    

    ! div height must be set