PHP查找并替换字符串中的html属性 [英] PHP find and replace html attribute in string

查看:43
本文介绍了PHP查找并替换字符串中的html属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从某些api获取iframe,然后将该iframe保存在某些变量中.

I get iframe from some api and i hold this iframe in some var.

我想搜索"高度"并将其值更改为其他值.与"滚动"相同.

I want to search for "height" and change his value to something else. the same with "scrolling".

例如:

<iframe src="someurl.com" width="540" height="450" scrolling="yes" style="border: none;"></iframe>

在php函数之后,iframe将为:

After the php function the iframe will be:

我们将高度"更改为600px,将滚动"更改为否

we have change the "height" to 600px and "scrolling" to no

<iframe src="someurl.com" width="540" height="600" scrolling="no" style="border: none;"></iframe>

我对此代码有解决方案:

i have solution with this code:

$iframe = preg_replace('/(<*[^>]*height=)"[^>]+"([^>]*>)/', '\1"600"\2', $iframe);

问题在于,在运行"preg_replace"之后,它会删除高度"之后的所有html属性.

the problem is that after the "preg_replace" run it remove all html attributes after the "height"

谢谢

推荐答案

您可以使用 DOMDocument.像这样:

function changeIframe($html) {

    $dom = new DOMDocument;
    $dom->loadHTML($html);
    $iframes = $dom->getElementsByTagName('iframe');
    if (isset($iframes[0])) {
        $iframes[0]->setAttribute('height', '600');
        $iframes[0]->setAttribute('scrolling', 'no');
        return $dom->saveHTML($iframes[0]);
    } else {
        return false;
    }
}

$html = '<iframe src="someurl.com" width="540" height="450" scrolling="yes" style="border: none;"></iframe>';

echo changeIframe($html);

通过这种方法,您可以根据需要修改iframe.

With this method you can modify iframe as you want.

谢谢.

这篇关于PHP查找并替换字符串中的html属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆