Andrei
Andrei

Reputation: 1005

Convert all images into clickable A tags with img inside

I have a block of html with a lot of <img src="..."/> inside of it.

Now I'm looking for a way to make this:

<img src="lol.jpg"/> into:

<a href="lol.jpg" class="image_inside_text" target="_blank">
<img src="lol.jpg"/>
</a>

The idea is to make images open in a new page to view the full size image, and I'm adding a class in case I want to make it into a popup later on. I'm looking to do this in PHP, can someone please help me?

Thank you

Upvotes: 0

Views: 150

Answers (5)

Chris
Chris

Reputation: 92

You can use output buffering: ob_start and do something similar to this example and replacing the callback with what test30 suggested:

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

?>

Upvotes: 0

janinaj
janinaj

Reputation: 154

You can use 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>')
    });
});

Upvotes: 0

test30
test30

Reputation: 3654

He asked for solution in PHP (see tags).

$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);

Online version: http://ideone.com/pY2EWY

Upvotes: 1

LcSalazar
LcSalazar

Reputation: 16841

There are several ways of doing so... Most involving Javascript.

Take a look at jquery's method wrap(), that wraps any selected element into another element:

$("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/

Upvotes: 0

Ahmad
Ahmad

Reputation: 477

Well, just use some jquery, try this :

<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" />

Upvotes: 0

Related Questions