找到打开/关闭标签并替换?

时间:2014-04-11 09:26:36

标签: regex

我有字符串:

<p>Lorem ipsum dolor sit amet. <object width="500" height="500" type="application/x-shockwave-flash" 
data="http://www.abc.com/m/l5J16d65wOpT" style="display: block; margin-left: auto; margin-right: auto;">
<param value="always" name="allowscriptaccess">
</object> Lorem ipsum dolor sit amet</p> Lorem ipsum dolor sit amet

现在,我想在对象标记周围添加<div class="player"></div>,它将成为:

<p>Lorem ipsum dolor sit amet. <div class="player"><object width="500" height="500" type="application/x-shockwave-flash" 
data="http://www.abc.com/m/l5J16d65wOpT" style="display: block; margin-left: auto; margin-right: auto;">
<param value="always" name="allowscriptaccess">
</object></div> Lorem ipsum dolor sit amet</p> Lorem ipsum dolor sit amet

2 个答案:

答案 0 :(得分:1)

preg_replace在这里可能有用:)

$result = preg_replace('|(<object.*</object>)|sui', '<div class="player">$1</div>', $html);

答案 1 :(得分:0)

如果你想像这样替换它,那么只需使用普通的str_replace

//PHP
$myString = str_replace("<object>", "<div class=\"player\"><object>", $originalString);
$myString = str_replace("</object>", "</object></div>", $originalString);