0

This may seem like a no-brainier, but the thing is I wont know the length of the string in advance. My client has a pre-made/bought Blog which adds youtube videos into posts via its CMS - basically I want my function to search a string like the following:

<embed width="425" height="344" type="application/x-shockwave-flash"     pluginspage="http://www.macromedia.com/go/getflashplayer" src="http://www.youtube.com/somevid"></embed>

and regardless of the current width and height values, I want to replace them with my own constants e.g width="325" height="244". Could someone kindly explain the best way to go about this?

Many thanks in advance!!

Matt
  • 89
  • 1
  • 1
  • 10

2 Answers2

2

DOMDocument FTW!

<?php

define("EMBED_WIDTH", 352);
define("EMBED_HEIGHT", 244);

$html = <<<HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<embed width="425" height="344" type="application/x-shockwave-flash"
       pluginspage="http://www.macromedia.com/go/getflashplayer" src="http://www.youtube.com/somevid"></embed>


</body>
</html>
HTML;

$document = new DOMDocument();
$document->loadHTML($html);

$embeds = $document->getElementsByTagName("embed");

$pattern = <<<REGEXP
|
(https?:\/\/)?   # May contain http:// or https://
(www\.)?         # May contain www.
youtube\.com     # Must contain youtube.com
|xis
REGEXP;

foreach ($embeds as $embed) {
    if (preg_match($pattern, $embed->getAttribute("src"))) {
        $embed->setAttribute("width", EMBED_WIDTH);
        $embed->setAttribute("height", EMBED_HEIGHT);
    }
}

echo $document->saveHTML();
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
-2

You should use regex expressions to replace it. For instance:

    if(preg_match('#<embed .*type="application/x-shockwave-flash".+</embed>#Us', $originalString)) {
        $string = preg_replace('#width="\d+"#', MY_WIDTH_CONSTANT, $originalString);
    }

The ".*" means any character. Like we pass the "s" flag after the sharp, we also accept line breaks. The "U" flag means ungreedy. It will stop at the first closing embed tag found.

The "\d+" means one or more digits.

Jonathan Petitcolas
  • 4,254
  • 4
  • 31
  • 42
  • 2
    Please refrain from parsing HTML with RegEx as it will [drive you insane](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Use an [HTML parser](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php) instead. – Madara's Ghost Jun 29 '12 at 14:20