tags:

views:

60

answers:

4

Hi, 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;amp;hl=en_US&amp;amp;fs=1"&gt;&lt;/param&gt;&lt;param 
name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/W-WKYIgGBbU&amp;amp;hl=en_US&amp;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;amp;hl=en_US&amp;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..

+2  A: 

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]);
jigfox
Muhammad Sajid
+1  A: 

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

karlw
+1, looks interesting
MartyIX
A: 

You can parse HTML using Tidy and SimpleXML:

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

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;amp;hl=en_US&amp;amp;fs=1"&gt;&lt;/param&gt;&lt;param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/W-WKYIgGBbU&amp;amp;hl=en_US&amp;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);

?>
ADAM