这应该有效:
preg_match("/<embed.*\/embed>/mi",$str,$matches);
$output = preg_replace(array('/width="\d+"/i','/height="\d+"/i'),array('width="30"','height="40"'),$matches[0]);
假设你总是能得到格式良好的 html,http://simplehtmldom.sourceforge.net/ 会很有帮助。
您可以使用 Tidy 和 SimpleXML 解析 HTML:
我会做这样的事情
<?php
$string = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/W-WKYIgGBbU&hl=en_US&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/W-WKYIgGBbU&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="100" height="100"></embed></object>';
$pattern = '/.*src="(.*?)".*/';
$replacement = '<embed src="\\1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="100" height="100"></embed>';
echo preg_replace($pattern, $replacement, $string);
?>
在直观、不言自明的脚本中使用合法的 DOM 解析器来根据需要隔离、更新和输出。
代码:(演示)
$str = <<<HTML
<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/W-WKYIgGBbU&hl=en_US&fs=1"></param><param
name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/W-WKYIgGBbU&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always"
allowfullscreen="true" width="100" height="100"></embed>
</object>
HTML;
$width = 30;
$height = 40;
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$embed = $dom->getElementsByTagName('embed')->item(0);
$embed->setAttribute('width', $width);
$embed->setAttribute('height', $height);
echo $dom->saveHTML($embed);
输出:
<embed src="http://www.youtube.com/v/W-WKYIgGBbU&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="30" height="40"></embed>