-2

I have a html string of iframe where width and it's value is included. I want to replace the width's value by regex in php. For example, I am getting a value dynamically as

<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>

I want to change the value of width by the regular expression. Can you help me someone.

StreetCoder
  • 9,871
  • 9
  • 44
  • 62

2 Answers2

1

Avoid using RegEx in XML/HTML documents, there are a performant libraries to do that, unless there a very very very good reason for that

Try with this code to achieve your job

<?php
    $html       = '<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>';
    $doc        = new DOMDocument();
    $doc->loadHTML($html);
    $elements   = $doc->getElementsByTagName('iframe');

    foreach($elements as $el) {
        $el->setAttribute('width', '1024');
    }
    print $doc->saveHTML();

OUTPUT

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><iframe width="1024" height="315" src="" frameborder="0" allowfullscreen></iframe></body></html>     
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
  • far as i can tell, he don't want the !DOCTYPE html public~~ stuff added, he just want the iframe code.try: print $doc->saveHTML($doc->getElementsByTagName('iframe')->item(0)); – hanshenrik Nov 28 '15 at 12:21
  • 1
    You can also use `$doc->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);` to prevent the doctype and the html, head tags to be automatically added. – Casimir et Hippolyte Nov 28 '15 at 15:39
  • it's awesome solution man. It works directly. Unfortunately I had lake of knowledge about this technique. Thanks – StreetCoder Nov 29 '15 at 03:30
1

sounds like a really bad idea, but here goes... something like

<?php
header('content-type:text/plain;charset=utf8');
$str=base64_decode('PGlmcmFtZSB3aWR0aD0iNTYwIiBoZWlnaHQ9IjMxNSIgc3JjPSIiIGZyYW1lYm9yZGVyPSIwIiBhbGxvd2Z1bGxzY3JlZW4+PC9pZnJhbWU+');
$ret=preg_replace('/(\<iframe.*?width\=)\"(.*?)\"/','${1}"999"',$str);
var_dump($str,$ret);

will change width to 999... but you should really use a proper HTML parser instead, like DOMDocument.

$domd=@DOMDocument::loadHTML($str);
$domd->getElementsByTagName('iframe')->item(0)->setAttribute('width',999);
echo $domd->saveHTML($domd->getElementsByTagName('iframe')->item(0));

will also change width to 999, and is much more reliable (for example, the regex will break if there is spaces or newlines between the width and = , although it would still be legal html.. sigh)

hanshenrik
  • 19,904
  • 4
  • 43
  • 89