2012-06-29 83 views
0

这可能看起来像一个不聪明的人,但事情是我不会事先知道字符串的长度。我的客户有一个预制的/买博客这增加了YouTube视频到通过其CMS岗位 - 基本上我想我的功能来搜索字符串类似如下:在字符串中的两个点之间替换文本

<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”。有人可以解释一下最好的方法吗?

非常感谢提前!

+0

cms是什么? WordPress的? – biziclop

+0

是的,DOMDocument可以帮助你,找到标签,替换属性并保存整个页面。 –

+0

不是wordpress,只是一些通用博客软件 – Matt

回答

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(); 
-2

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

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

“。*”表示任何字符。就像我们在尖锐之后传递“s”标志一样,我们也接受换行符。 “U”标志意味着未审理。它会在找到的第一个关闭嵌入标签处停止。

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

+2

请不要使用正则表达式解析HTML,因为它会[驱动你疯狂](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-自包含的标签/ 1732454#1732454)。改为使用[HTML解析器](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php)。 –

相关问题