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"
<?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);
?>
str_replace doesn't use regexps. Use this instead:
$str = preg_replace('/<iframe.*?>/', '', $str);
This will replace
<iframe something>
to empty string
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.
Adding to the last answer this is a more efficient regular expression for replacing multiple iframes.
$html = preg_replace('/(<iframe.+">)/is', '', $html);
来源:https://stackoverflow.com/questions/18653440/regular-expression-to-remove-an-iframe