2012-01-30 47 views
0

我需要在字符串中添加任何img標記,並在其周圍添加標記。PHP - 'wrap'<a>標記在字符串內的任何<img>標記

E.g.

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

需要與

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

我當前的腳本被替換爲:

$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 

這給了我下面的錯誤: 開捕致命錯誤:類對象一個DOMElement不能被轉換爲字符串

關於我在哪裏的任何想法goi恩錯了嗎?

+1

是對象的preg_replace支持字符串,只有數組。 – 2012-01-30 09:07:22

回答

2

隨着DOM方法,像這樣(未經測試,調試自己; 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); 
} 
0

$內容是不能轉換爲字符串的對象。
來測試它,使用var_dump($content);
你不能直接回顯它。它通過DOM提供
使用屬性和方法,你可以從這裏得到:DOM Elements

0

getElementsByTagName回報的DOMNodeList對象包含所有匹配的元素。所以$ tag是DOMNodelist :: item,因此不能直接在字符串操作中使用。您需要獲得nodeValue。更改foreach代碼如下:

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

我想這裏的DOMDocument不是從字符串中加載HTML。一些奇怪的問題。我更喜歡你使用DOM解析器如SimpleHTML

你可以用它喜歡:

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

希望這有助於:)

腳本中的$內容
+0

更好的方法http://stackoverflow.com/questions/8871356/wrap-all-image-tags-in-a-string-with-links – 2015-05-07 02:28:49