6

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"

Brandon
  • 16,382
  • 12
  • 55
  • 88
Analog
  • 201
  • 1
  • 2
  • 13

4 Answers4

10
<?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);
?>
  • This worked perfectly as well, in addition to the above answer i can replace specific content with my own content first then replace all other frames with nothing. – Analog Sep 15 '13 at 13:17
  • This is the only valid response on this page. – brett Dec 03 '19 at 15:33
1

str_replace doesn't use regexps. Use this instead:

$str = preg_replace('/<iframe.*?>/', '', $str);

This will replace

<iframe something>

to empty string

baao
  • 71,625
  • 17
  • 143
  • 203
user4035
  • 22,508
  • 11
  • 59
  • 94
  • 1
    This worked great, but i had to add a ' after '// because the page was not loading anything if it wasn't there. – Analog Sep 07 '13 at 22:34
0

str_replace() does not support regular expressions. You are after preg_replace(). You will want a regex similar to:

$html = preg_replace('/<iframe>.*<\/iframe>/is', '', $html);

Although, as this is HTML you should avoid regexing and use an HTML parser instead.

juco
  • 6,331
  • 3
  • 25
  • 42
  • This does not work to remove an iframe. And it definitely does not work to remove multiple iframes. Consider the following string to test: `$str = '222';` – brett Dec 03 '19 at 15:31
-2

Adding to the last answer this is a more efficient regular expression for replacing multiple iframes.

$html = preg_replace('/(<iframe.+">)/is', '', $html);
Joe Barbour
  • 842
  • 9
  • 14
  • This does not work to remove an iframe. And it definitely does not work to remove multiple iframes. Consider the following string to test: `$str = '222';` – brett Dec 03 '19 at 15:32