开发者

Parsing string using PHP

I am using PHP & want to parse given string: Let say

$str = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/W-WKYIgGBbU&amp;hl=en_U开发者_运维知识库S&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>';

and I just need

$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="100" height="100"></embed>';

and set height and width to my custom value let say $width = 30 and $height = 40.

Thanks..


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


Assuming you are always going to get well formed html, http://simplehtmldom.sourceforge.net/ would be helpful.


You can parse HTML using Tidy and SimpleXML:

  1. Clean HTML with Tidy
  2. Find and modify <embed> tag with SimpleXML


i would do something like this

<?php

$string = '<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>';
$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);

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜