views:

124

answers:

4

I'd like to convert a normal link tag into an image tag,

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.

+1  A: 

With str_replace it should be

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

and

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

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.
zneak
A: 

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.
lamas
+1  A: 

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