0
votes

I'd like to convert my wordpress post img tags in my post to div background images. I currently have a function setup to add a class to the parent paragraph tag. Any idea how to edit the preg replace to change the img tag to a div and set the style="background-image: url("{img_src}");" with the img src?

My current function is:

function give_attachments_class($content){
  $classes = 'class="img_wrap"';
  $firstH2 = 'class="first_h2"';
  $img_match = preg_match("/(<p.*?)(.*?><img)/", $content, $img_array);
  $youtube_match =preg_match("/(<p><span)+[ ]+(class=)+['\"]embed-youtube/", $content, $output_array);


  if(!empty($img_match))
   {
    $content = preg_replace('/(<p.*?)(.*?><img)/', '$1 ' . $classes . '$2', $content);

  }

  if(!empty($youtube_match))
   {
    $content = preg_replace("/(<p><span)+[ ]+(class=)+['\"]embed-youtube/", "<p class=\"img_wrap\"><span class='embed-youtube", $content);
   }

  $content = preg_replace('/<div .*?class="(.*?video-container.*?)">(.*?)<\/div>/','<p class="img_wrap"><span class="embed-youtube">$2</span></p>',$content);

  return $content;
}
1

1 Answers

0
votes

Try this for your img tags. Dump you db before just in case.

$pattern = '/img([^>]*?>)/i';
$replacement = 'div$1</div>';
echo preg_replace($pattern, $replacement, $content);

Update 2

This will get rid of the style attributes on your img tags, then builds new style tags with the required css, while replacing the src tags, then turns the img tags to divs. It also keeps other attributes like title type whatever.

$content = "<img type=\"asd\" style=\"color:red\" src=\"qwe\" class=\"asd\" > lorem 
ipsum <img type=\"asd\" style=\"color:red\" src=\"qwe\" class=\"asd\" >";

$pattern = '/style=".*?"/';
$replacement = "";
$result = preg_replace($pattern, $replacement, $content);


$pattern = '/src="(.*?)"/';
$replacement = "style=\"background-image:url($1);\"";
$result = preg_replace($pattern, $replacement, $result);


$pattern = '/img((.*?)(style=".*?")((.*?)(>|\/>)))/';
$replacement = 'div$2$3'.'$5></div>';
echo preg_replace($pattern, $replacement, $result);