Find and replace an iframe

Using Search Regex to find and replace HTML elements is a common task and it can be achieved using regular expressions. Although HTML is not ideally suited to regular expressions, it is generally possible to achieve a fairly robust result if your content isn’t complicated.

In this set of examples we’ll look at the HTML iframe element.

The most basic situation is to remove all iframes from content.

The following regular expression used in Search Regex as the search value will achieve this. Remember to enable the regex flag.

<iframe.*?(/iframe>|/>)

This will match <iframe attributes></iframe> as well as <iframe attributes />.

Combine this with a global replace with ‘remove’ and it will then remove all iframes.

What if you want to replace the iframe with something else instead. For example, a link that points at the site the iframe was referencing?

<iframe.*?src="(.?)".*?(/iframe>|/>)

You can then combine this with a replacement value of:

<a href="$1">$1</a>

This will transform all iframes to links, with the link text being the URL.

You may need to perform some additional HTML clean up if, for example, the iframe is contained within paragraphs and you want to remove empty pararaphs.

Published
Categorized as tip