Scott Bowers
Scott Bowers

Reputation: 1

PHP - 'wrap' <a> tag around any <img> tag within a string

I need to take any img tag within a string, and add an a tag around it.

E.g.

$content= "Click for more info <img src="\http://www.domain.com/1.jpg\"" />";

Would need to be replaced with

"Click for more info <a href=\"http://www.domain.com/1.jpg\"<img src="\http://www.domain.com/1.jpg\"" /></a>";

My current script is:

$content = $row_rsGetStudy['content'];

$doc = new DOMDocument();
$doc->loadHTML($content);
$imageTags = $doc->getElementsByTagName('img');

foreach($imageTags as $tag) {
    $content = preg_replace("/<img[^>]+\>/i", "<a href=\"$tag\"><img src=\"$tag\" /></a>", $content); 
}

echo $content

This gives me the following error: Catchable fatal error: Object of class DOMElement could not be converted to string

Any ideas on where I'm going wrong?

Upvotes: 0

Views: 2582

Answers (4)

Sabari
Sabari

Reputation: 6335

I think here the DOMDocument is not loading HTML from the string. Some strange issue. I prefer you to use DOM parser such as SimpleHTML

You can use it like :

  $content= 'Click for more info <img src="http://www.domain.com/1.jpg" />';

  require_once('simple_html_dom.php');

  $post_dom = str_get_html($content);

  $img_tags = $post_dom->find('img');

  $images = array();

  foreach($img_tags as $image) {
      $source = $image->attr['src'];
      $content = preg_replace("/<img[^>]+\>/i", "<a href=\"$source\"><img src=\"$source\" /></a>", $content); 
 }

 echo $content;

Hope this helps :)

Upvotes: 0

Lucky Murari
Lucky Murari

Reputation: 12782

getElementsByTagName returns DOMNodeList object containing all the matched elements. So $tag is DOMNodelist::item here and hence can't be used directly in string operations. You need to get nodeValue. Change the foreach code as follows:

foreach($imageTags as $tag) {
    $content = preg_replace("/<img[^>]+\>/i", "<a href=\"$tag->nodeValue\"><img src=\"$tag->nodeValue\" /></a>", $content); 
}

Upvotes: 0

Ket.
Ket.

Reputation: 774

$content is an object which can not be converted to string.
to test it, use var_dump($content);
you can't directly echo it.
use properties and methods which offer by DOM, you can get from here: DOM Elements

Upvotes: 0

Wrikken
Wrikken

Reputation: 70460

With DOM methods, something like this (untested, debug yourself ;P )

foreach($imageTags as $tag) {
    $a = $tag->ownerDocument->createElement('a');
    $added_a = $tag->parentNode->insertBefore($a,$tag);
    $added_a->setAttribute('href',$tag->getAttribute('src'));
    $added_a->appendChild($tag);
}

Upvotes: 2

Related Questions