2010-03-07 37 views
1

我想一個正常的鏈接標籤轉換爲圖像標籤,轉換標準的鏈接,圖片鏈接

我將如何轉換這下面,

<a href="images/first.jpg">This is an image.</a> 

<a href="images/second.jpg">This is yet another image.</a> 

<a href="images/third.jpg">Another image.</a> 

進入這個用PHP,

<img src="dir/images/first.jpg">This is an image. 

<img src="dir/images/second.jpg">This is yet another image. 

<img src="dir/images/third.jpg">Another image. 

源中可以有任意數量的鏈接。

謝謝。

+0

inb4使用HTML解析器。 – zneak 2010-03-07 21:49:59

回答

1

使用正則表達式:

$text = preg_replace('^<a href="(.+)">(.+)</a>^', '<img src="dir/$1">$2', $text); 

輸出:

<img src="dir/images/first.jpg">This is an image. 

    <img src="dir/images/second.jpg">This is yet another image. 

    <img src="dir/images/third.jpg">Another image. 
1

隨着str_replace函數應該是

$source = str_replace('<a href="images/', '<img src="dir/images/', $source); 

$source = str_replace('</a>', '', $source); 
0

由於<a>標籤不能嵌套的,如果你準備把它在一定優勢的情況下失敗了,你可以使用普通的表達到這裏一個非常安全的程度。

$text = '<a href="images/first.jpg">This is an image.</a> 
<a href="images/second.jpg">This is yet another image.</a> 
<a href="images/third.jpg">Another image.</a>'; 

$text = preg_replace('#<a.+?href="([^"]+)".*?>(.+?)</a>#i', '<img src="dir/\1" alt="">\2', $text); 
echo $text; 

這給:

<img src="dir/images/first.jpg" alt="">This is an image. 
<img src="dir/images/second.jpg" alt="">This is yet another image. 
<img src="dir/images/third.jpg" alt="">Another image. 
1

與HTML解析器:

<?php 

$content = '<a href="images/first.jpg">This is an image.</a> 

<a href="images/second.jpg">This is yet another image.</a> 

<a href="images/third.jpg">Another image.</a>'; 

$html = new DOMDocument(); 

$html->loadHTML($content); 

$links = $html->getElementsByTagName('a'); 

$new_html = new DOMDocument(); 

foreach($links as $link) { 
    $img = $new_html->createElement('img'); 
    $img->setAttribute('src', 'dir/'.$link->getAttribute('href')); 
    $new_html->appendChild($img); 
    $new_html->appendChild($new_html->createTextNode($link->nodeValue)); 
} 


echo $new_html->saveHTML();