Replace iframe with link with regex

Related searches

I currently have this string:

"<p><iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="" width="640"></iframe></p>"

I'd like to remove the whole iframe element (<iframe>...</iframe>) and replace it with an <a> link to the url in the src attribute:

<p><a href="">Link to youtube</a></p>

Currently, I have this regex:

$res = preg_replace('/src="(.+?)"/', '/<a href="$1">Link to youtube</a>/', $str);

With this regex, I'm able to replace the src attribute with an a element. However, I'd like to replace the whole iframe element.

What is the easiest way to achieve this?

Use this RegEx:


And this Replace:

<a href=$1>Link to youtube</a>

Which gives you the following preg_replace():

$res = preg_replace('/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', '/<a href=$1>Link to youtube</a>/', $str);

Live Demo on Regex101

The RegEx captures all the data before and after the src, and then is therefore also replaced.

How it works:

<iframe          # Opening <iframe
\s+              # Whitespace
.*?              # Optional Data (Lazy so as not to capture the src)
\s+              # Whitespace
src=             # src Attribute
    (".*?")          # src Data (i.e. "")
.*?              # Optional Data (Lazy so as not to capture the closing </iframe>)
<\/iframe>       # Closing </iframe>

Thank to @AlexBor for informing me that the following is slightly more efficient. I would suggest using this RegEx instead:


Replaced src=(".*?") (lazy) with src=("[^"]+") (greedy)

Javascript regular expression to replace iframe to clickable YouTube , If you want to grab the whole iframe string and replace it: Use: to extract youtube video ID and replace <iframe /> with <a /> var url = /src="(. Conditional Regex Replacement in Text Editor Often, the need arises to replace matches with different strings depending on the match itself. For instance, let's say you want to match words for colors, such as red and blue , and replace them with their French equivalents— rouge and bleu .

Using a DOM parser like DOMDocument is not going to let you down. Unlike regex, it is HTML "aware". I'll add some flags to my loadHTML() call to clear out some additional html tag generation, iterate all occurrences of <iframe> tags, create a new <a> element for each occurrence, fill it with the desired values, then replace the <iframe> tag with the new <a> tag.

Code: (Demo)

$html = <<<HTML
<p><iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="" width="640"></iframe></p>

$dom = new DOMDocument;
foreach ($dom->getElementsByTagName('iframe') as $iframe) {
    $a = $dom->createElement('a');
    $a->setAttribute('href', $iframe->getAttribute('src'));
    $a->nodeValue = "Link to youtube";
    $iframe->parentNode->replaceChild($a, $iframe);
echo $dom->saveHTML();


<p><a href="">Link to youtube</a></p>

Regular expression to remove an iframe, I'm trying to use str_replace to replace all iframes with my own content. This will turn every absolute link in an <a> tag into a relative link: <?php $html = 'Some� This incorrectly extracts links that have been commented out. The following snippet does not contain a link: new Object[] { “abc hahaha <!– google –>” } Also, it includes tags in link text, fails to exclude comments in link text, and fails to recognize links that are inside or at any point after another tag in the document that starts with “<a".

The easiest way would be to take out the src attribute with preg_match() and then use it to create a element.


$string = "<p><iframe allowfullscreen=\"\" class=\"media-element file-default\" data-fid=\"2219\" data-media-element=\"1\" frameborder=\"0\" height=\"360\" src=\"\" width=\"640\"></iframe></p>\n";

if( preg_match( '#src=\\"([^ ]*)\\"#', $string, $matches ) === 1 ){
    $string = '<a href="' . $matches[ 1 ] . '">Link to youtube</a>';
    echo $string;

// outputs <a href="">Link to youtube</a>

iframe regex, Match an email address � date format (yyyy-mm-dd) � Url Validation Regex | Regular Expression - Taha � Match or Validate phone number � match whole word Click link: replace src of iframe with link src How? Tried the HTML way by changing the target name to the same one used in iframe id and name… Still the link makes the batchgeo map go away

Replace height in an iframe, Regular Expression to. Replace height in an iframe Url Validation Regex | Regular Expression - Taha � Match or Validate phone number � match whole word Iframe is obsolete because it is not indexed by google, what's inside the iframe is not on display, and theoretically it would be slower, so maybe my teacher say to replace iframe. Is there any way to convert an iframe to a div (or something else I do not know, it does not have to be div, but can not be an iframe), but works like an iframe.

Need a regex ninja's help with replacing a YouTube string , This will match groups iframe , anything inbetween iframe and the I give you a demo (when you click on the link, make sure to switch to� All the iframe attributes are in a stylesheet, and i am sure it is uploaded to the right spot and the links are correct Question is, why would firefox view it correctly when its viewed locally, and not when it is uploaded it to the web.

iframe regex. Comments. Post Posting Guidelines Formatting - Now. Top Regular Expressions. uk postcodes RegEx Allowing Number Only pdf or jpg Find YouTube Links

  • Minor addition: replace src=(".*?") with src=("[^"]+") to use pcre engine optimizations.
  • @AlexBor Is that more efficient? I have always wondered about this, using a lazy .*? or your method.
  • The effectiveness depends on string length in src attribute. If you use lazy quantifier ".*?" engine will do n(string length) steps. If you use greedy quantifier "[^"]+" engine will do constant steps (1) if in string after engine cursor position there is a quotation mark character. In a really small strings there are no benefits regardless of the approach you use. But if you will use this regex with long text it will works faster. How to work regex engine you can see in regex debugger: lazy version:, greedy version:
  • @AlexBor Thanks, nice explanation. I'll update the answer, and you get a user profile link! ;)
  • The RegEx fails if the src-attribute comes first, since it's checking for "whitespace-optional data-whitespace", while there will be no two whitespaces before the first attribute - this can be fixed by setting one of the two whitespaces to optional. Additionally, if the attributes are chopped down (e.g. <iframe width="500"\n\theight="500"\n\tsrc=""></iframe>, you need to add the "single line"-flag. The resulting RegEx would be /<iframe\s+.*?\s?src=("[^"]+").*?<\/iframe>/s - although using a DOM-parser would probably serve you better here
  • This approach doesn't replace iframe tag as wants author.
  • This approach does replace iframe tag with a tag while using different functions. Author didn't specify that he needs to use preg_replace(). This approach is easier to understand, write and read and result is the same.