user2413244
user2413244

Reputation: 241

PHP find and replace html attribute in string

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".

For example:

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

After the php function the iframe will be:

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);

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

Thanks

Upvotes: 1

Views: 3763

Answers (2)

Taron Saribekyan
Taron Saribekyan

Reputation: 1390

You can use DOMDocument for it. Something like this:

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);

With this method you can modify iframe as you want.

Thanks.

Upvotes: 3

Mark
Mark

Reputation: 3272

An example as you requested:

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

$str = preg_replace('/height=[\"\'][0-9]+[\"\']/i', 'height="600"', $str);
$str = preg_replace('/scrolling=[\"\']yes[\"\']/i', 'scrolling="no"', $str);

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

Upvotes: 1

Related Questions