preg_replace所有img标签与其他东西

时间:2012-02-07 14:56:00

标签: php html css

基本上我需要做的就是替换所有

<img src="random image goes here" class="random class goes here" alt="random alt goes here" />

<table>
    <a href="#">src="random image goes here" class="random class goes here" alt="random alt goes here" /></a>
</table>

在内容中。我尝试用preg_replace来做,但没有成功,也许你可以尝试帮助我?

这是我尝试过的 -

$content = preg_replace('/"><img class=/', '"><table class="image-caption aligncenter"><tr><td><div><a href="#" target="blank"><img class=', $content);
$content = preg_replace('/ \><\a>/i', ' /></a></div></td></tr></table></a>', $content);

2 个答案:

答案 0 :(得分:2)

缺乏更好的背景:

$content = preg_replace(
    '/(<img[^>]+>)/',
    "<table><tr><td><a href=\"#\">$1</a></td></tr></table>",
    $content
);

检查http://php.net/manual/en/function.preg-replace.php

答案 1 :(得分:0)

preg_replace('/(<img.*>)/', '<table><a href="#">$1</a></table>', $content);

我已将您的要求直接翻译为代码。但是问题中的HTML是不正确的,因为表应该至少在tr和td上。在我的代码中容纳那些并且它可以正常工作

根据您在下面的问题中提供的代码段进行修改

preg_replace('/(<img.*>)/', '<table><tr><td><div><a href="#" target="blank">$1</a></div></td></tr></table></a>', $content);