简体   繁体   English

php regex 更改值 html 属性

[英]php regex to change the value html attribute

I have a html string of iframe where width and it's value is included.我有一个 iframe 的 html 字符串,其中包含宽度和它的值。 I want to replace the width's value by regex in php.我想用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避免在XML/HTML文档中使用 RegEx,有一个高性能库可以做到这一点,除非有非常非常好的理由

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.将宽度更改为 999...但您确实应该使用适当的 HTML 解析器,例如 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)还将宽度更改为 999,并且更可靠(例如,如果宽度和 = 之间有空格或换行符,正则表达式将中断,尽管它仍然是合法的 html .. 叹气)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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