开发者

Convert standard link to image link

I'd like to convert a normal link tag into an image tag,开发者_StackOverflow社区

How would I convert this following,

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

Into this with 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.

There can be any number of links in the source.

Thanks.


Use regex:

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

Output:

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


With str_replace it should be

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

and

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


With an HTML-parser:

<?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();


Since <a> tags cannot be nested, and if you're ready to have it fail under certain edge cases, you can use regular expressions to a pretty safe degree here.

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

This gives:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜