将标准链接转换为图像链接

时间:2010-03-07 21:48:12

标签: php html hyperlink

我想将普通的链接标记转换为图像标记,

我将如何转换以下内容,

<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.

源中可以有任意数量的链接。

感谢。

4 个答案:

答案 0 :(得分:1)

使用str_replace时,它应该是

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

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

答案 1 :(得分: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.

答案 2 :(得分: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();

答案 3 :(得分:0)

由于<a>标签无法嵌套,并且您已准备好在某些边缘情况下使其失败,因此您可以在此处使用正则表达式。©/ p>

$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.
相关问题