简体   繁体   中英

php regex to change the value html attribute

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.

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>     

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM