替换字符串中两点之间的文本

时间:2012-06-29 14:15:15

标签: php html regex

这可能看起来像一个没有脑子的人,但问题是我不会提前知道字符串的长度。我的客户有一个预制/购买的博客,通过其CMS将YouTube视频添加到帖子中 - 基本上我希望我的功能搜索如下字符串:

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

并且无论当前的宽度和高度值如何,我都想用我自己的常量替换它们,例如width =“325”height =“244”。有人可以解释一下这个问题的最佳方法吗?

非常感谢提前!!

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:-2)

您应该使用正则表达式来替换它。例如:

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

“。*”表示任何字符。就像我们在锋利之后传递“s”旗帜一样,我们也接受换行符。 “U”标志表示 ungreedy 。它将在找到的第一个封闭嵌入标签处停止。

“\ d +”表示一个或多个数字。

相关问题