phphtml-parsingsetattribute

Parse HTML string, isolate `<embed>` tag, and update its width and height attribute values


I want to parse a string containing HTML, isolate the <embed> tag and update its width and height attribute values.

Sample input:

$str = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/W-WKYIgGBbU&amp;hl=en_US&amp;fs=1"></param><param 
name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/W-WKYIgGBbU&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" 
allowfullscreen="true" width="100" height="100"></embed>
</object>';

$width = 30;
$height = 40;

Desired output:

$output = '<embed src="http://www.youtube.com/v/W-WKYIgGBbU&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" 
allowfullscreen="true" width="30" height="40"></embed>';

Solution

  • This should work:

    preg_match("/<embed.*\/embed>/mi",$str,$matches);
    $output = preg_replace(array('/width="\d+"/i','/height="\d+"/i'),array('width="30"','height="40"'),$matches[0]);