2012-01-30 29 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