Regular expression to remove an iframe

Analog picture Analog · Sep 6, 2013 · Viewed 8.7k times · Source

I'm trying to use str_replace to replace all iframes with my own content. I believe I can use regular expression but not exactly sure how to remove all content within the iframe tag.

Since I'm not really sure how to achieve this, below is what I have been using. But it's only replacing "iframe" with nothing so when a page is loaded anywhere an iframe would load now just shows the URL that would have been loaded if the iframe were to parse properly.

$toremove = str_replace("iframe", "", $toremove);

Here is an example output of what gets loaded instead of the iframe when using the code above. You can see that it's the whole iframe just without the word "iframe" which is breaking the iframe (which is better then displaying it)

< src="http://cdn2.adexprt.com/exo_na/center.html" width="728" height="90" frameborder="0" scrolling="no"> 

But now I want to completely remove the iframe and all it's content so I can place my own content in it's place without showing the old broken code as well. But I'm not sure how to edit my str_replace with a regular expression and not just the work "iframe"

Answer

user1646111 picture user1646111 · Sep 6, 2013
<?php
$iframe='<iframe src="http://cdn2.adexprt.com/exo_na/center.html" width="728" height="90" frameborder="0" scrolling="no">
</iframe>';
$pattern = "#<iframe[^>]+>.*?</iframe>#is";
echo preg_replace($pattern, "", $iframe);
?>