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&hl=en_U开发者_运维知识库S&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>';
and I just need
$output = '<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>';
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:
- Clean HTML with Tidy
- 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&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);
?>
精彩评论