user1149859
user1149859

Reputation: 23

Wrap All Image Tags In A String With Links

Trying to automatically wrap all image tags within a field that's currently managed with CKEditor. Would really like to handle it all with PHP.

So this would be an example of a field's random contents:

<p>
    Intro text here<br />
    <img alt="sample desc" src="/images/example1.jpg" />
    Long article text here...
    <img alt="sample desc" src="/images/example2.jpg" />
    Short article text here...
    <img alt="sample desc" src="/images/example3.jpg" />
</p>

And I would need to change the above code to this, wrapping each image tag with a link using a unique id, href matching the img's source and title matching alt text:

<p>
    Intro text here<br />
    <a id="image1" href="/images/example1.jpg" title="sample desc">
       <img alt="sample desc" src="/images/example1.jpg" />
    </a>
    Long article text here...
    <a id="image2" href="/images/example2.jpg" title="sample desc">
       <img alt="sample desc" src="/images/example2.jpg" />
    </a>
    Short article text here...
    <a id="image3" href="/images/example3.jpg" title="sample desc">
       <img alt="sample desc" src="/images/example3.jpg" />
    </a>
</p>

Thanks for any help you can provide!

Upvotes: 2

Views: 643

Answers (2)

Rajat Singhal
Rajat Singhal

Reputation: 11264

Give an id to the p..lets say main_p in order to select it..or you can choose any other selector..

$(document).ready(function() {
    var i=1;
        $("#main_p img").each(function(){
$(this).wrap('<a id=image'+i+++' href='+$(this).attr("src")+' title="sample desc"/>');
})
});

This will make exectly what code you have writtten second..

Live Demo

Upvotes: 0

mario
mario

Reputation: 145482

If it's arbitrary HTML that comes from external sources then it's most simple with e.g.

$html = htmlqp($html);
foreach ($html->find("img") as $img) {
    $img->wrap("<a href='{$img->attr('src')}'></a>");
}
print $html->top("p")->html();

You might want to inject id= and title= likewise in the loop, but that's about it.

Upvotes: 2

Related Questions