1

I have my videos wrapped in a custom div. It looks like this:-

<div class="yt">
  <iframe>....Video code....</iframe>
</div>

I want to remove <div class="yt"> and </div> but keep the iframe. I tried using preg_replace using this code:-

$content = preg_replace('#<div class="yt">(.*?)</div>#', '', $content);
return $content;

This removes the whole div. Can somebody help me?

Desired output

<iframe>....Video code....</iframe>
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user1928108
  • 101
  • 2
  • 11
  • The most efficient way would be to manually move the children, see https://stackoverflow.com/questions/20910147/how-to-move-all-html-element-children-to-another-parent-using-javascript/20910214 – Thomas Nov 05 '18 at 16:45
  • So, I'll have to use JS not PHP? I was wondering if there was a way to do it with PHP. – user1928108 Nov 05 '18 at 16:49
  • sorry, my mistake. I've added an answer using PHP. – Thomas Nov 05 '18 at 17:02

1 Answers1

2

You can do it with a Regex but you'll have to make two changes:

(.*?) doesn't match newline characters. So replace . with [\s\S] (source: Any character including newline - Java Regex)

And to preserve the contents you need to replace it with your capturing group $1.

Final code:

$content = preg_replace('#<div class="yt">([\s\S]*?)</div>#', '$1', $content);

Demo: https://regex101.com/r/oHiPt2/1

You could improve the regex or use trim() if you need to remove the surrounding white space.

Thomas
  • 8,426
  • 1
  • 25
  • 49