0

What's a regex pattern (in PHP) that replaces img string with links, where tag img URL is used as the anchor text for the link? For example:

function foo($uri) {
    $url = parse_url($uri);
    $paths = explode('/', $url['path']);
    return sprintf("%s://%s/%s", $url['scheme'], 'http://mywebsite.com', end($paths));
}
$str='text <img src="http://example.com/images1.jpg" />text <img src="http://example.com/img/images2.jpg" /> ending text';
$url = '?<=img\s+src\=[\x27\x22])(?<Url>[^\x27\x22]*)(?=[\x27\x22]';
$str_rep = preg_replace($url, foo($url), $str);
echo $str_rep;

becomes:

text <img src="http://mywebsite.com/images1.jpg" />
 text <img src="http://mywebsite.com/images2.jpg" /> ending text

How to fit it ?

Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102

1 Answers1

0

Parsing (x)HTML with regular expressions is usually a bad idea. I propose the following DOM-based solution:

$html = 'text <img src="http://mywebsite.com/images1.jpg" />' . "\n" 
  . ' text <img src="http://mywebsite.com/images2.jpg" /> ending text';

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($html);
libxml_use_internal_errors(false);

foreach ($domd->getElementsByTagName("img") as $image) {
  $link = $domd->createElement("a");
  $link->setAttribute("href", $image->getAttribute("src"));
  $image->parentNode->replaceChild($link, $image);
  $link->appendChild($image);
}

//this loop is neccesary so there's no doctype, html and
// some other tags added to the output 
$doc = new DOMDocument();
foreach ($domd->documentElement->firstChild->childNodes as $child)
  $doc->appendChild($doc->importNode($child, true));

var_dump($doc->saveHTML());

The output is:

<p>text <a href="http://mywebsite.com/images1.jpg"><img src="http://mywebsite.com/images1.jpg"></a>
 text <a href="http://mywebsite.com/images2.jpg"><img src="http://mywebsite.com/images2.jpg"></a> ending text</p>
Community
  • 1
  • 1
Maerlyn
  • 33,687
  • 18
  • 94
  • 85