PHP Preg Replace – Match String with Space – WordPress

I’m trying to scan my wordpress content for:

<p><span class="embed-youtube">some iframed video</span></p>   

and then change it into:

Read More
<p class="img_wrap"><span class="embed-youtube">some iframed video</span></p>  

using the following code in my function.php file in my theme:

$classes = 'class="img_wrap"';
$youtube_match = preg_match('/(<p.*?)(.*?><span class="embed-youtube")/', $content, $youtube_array);

if(!empty($youtube_match))
 {
  $content = preg_replace('/(<p.*?)(.*?><span class="embed-youtube")/', '$1 ' . $classes . '$2', $content);
 }

but for some reason I am not getting a match on my regex nor is the replace working. I don’t understand why there isn’t a match because the span with class embed-youtube exists.

UPDATE – HERE IS THE FULL FUNCTION

function give_attachments_class($content){
   $classes = 'class="img_wrap"';
   $img_match = preg_match("/(<p.*?)(.*?><img)/", $content, $img_array);
   $youtube_match = preg_match('/(<p.*?)(.*?><span class="embed-youtube")/', $content, $youtube_array);

   // $doc = new DOMDocument;
   // @$doc->loadHTML($content); // load the HTML data

   // $xpath = new DOMXPath($doc);
   // $nodes = $xpath->query('//p/span[@class="embed-youtube"]');

   // foreach ($nodes as $node) {
   //    $node->parentNode->setAttribute('class', 'img_wrap');
   // }

   // $content = $doc->saveHTML();


   if(!empty($img_match))
    {
     $content = preg_replace('/(<p.*?)(.*?><img)/', '$1 ' . $classes . '$2', $content);
    }
   else if(!empty($youtube_match))
    {
     $content = preg_replace('/(<p.*?)(.*?><span class="embed-youtube")/', '$1 ' . $classes . '$2', $content);
    }

   $content = preg_replace("/<img(.*?)src=('|")(.*?).(bmp|gif|jpeg|jpg|png)(|")(.*?)>/", '<img$1 data-original=$3.$4 $6>' , $content);

   return $content;
  }

add_filter(‘the_content’,’give_attachments_class’);

Related posts

2 comments

  1. Instead of using regex, make effective use of DOM and XPath to do this for you.

    $doc = new DOMDocument;
    @$doc->loadHTML($html); // load the HTML data
    
    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query('//p/span[@class="embed-youtube"]');
    
    foreach ($nodes as $node) {
       $node->parentNode->setAttribute('class', 'img_wrap');
    }
    
    echo $doc->saveHTML();
    
  2. Here is a quick and dirty REGEX I did for you. It finds the entire string starting with p tag, ending p tag, span also included etc. I also wrote it to include single or double quotes for you since you never know and also to include spaces in various places. Let me know how it works out for you, thanks.

    (<p )+(class=)['"]+img_wrap+['"](><span)+[ ]+(class=)+['"]embed-youtube+['"]>[A-Za-z0-9='" ]+(</span></p>)
    

    I have tested it on your code and a few other variations and it works for me.

Comments are closed.