我有一块html,里面有很多<img src="..."/>
现在我正在寻找一种方法来制作这个:
<img src="lol.jpg"/>
进入:
<a href="lol.jpg" class="image_inside_text" target="_blank">
<img src="lol.jpg"/>
</a>
这个想法是在一个新页面中打开图像以查看全尺寸图像,我正在添加一个类,以防以后我想将其弹出。我想用PHP做这件事,有人能帮我吗?
感谢
他要求在PHP中找到解决方案(参见标签)。
$string = <<<EOD
<img src="lol.jpg">
<img src="lol.jpg"/>
<img src="lol.jpg" alt="sufix"/>
<img alt="prefix" src="lol.jpg"/>
EOD;
$pattern = '/<img[^>]+src="([a-z.]+)"[^>]*>/i';
$replacement = '<a href="${1}">${0}</a>';
echo preg_replace($pattern, $replacement, $string);
联机版本:http://ideone.com/pY2EWY
好吧,只需要使用一些jquery,试试这个:
<script>
$(function(){
$('.thisimg').replace('<a href="your location" class="your class" target="_blank"><img src="your src" class="thisimg" /></a>');
});
</script>
<img src="your src" class="thisimg" />
有几种方法……大多数都涉及Javascript。
看看jquery的方法wrap()
,它将任何选定的元素封装到另一个元素中:
$("img").each(function() {
var href = $(this).attr("href");
$(this).wrap("<a href='"+href+"' class='image_inside_text' target='_blank'></a>");
});
http://api.jquery.com/wrap/
您可以使用jQuery:
$(function(){
$('img').each(function() {
var src = $(this).attr("src");
$( this ).replaceWith('<a href="' + src +'" class="image_inside_text" target="_blank"><img src="' + src + '"/></a>')
});
});
您可以使用输出缓冲:ob_start并执行类似于此示例的操作,并将回调替换为test30建议的内容:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>