将图像url替换为img标签


Replace image url with img tag

我正在尝试用img标签替换字符串中的url。

我有这个工作,但是,它也取代了锚标记内的url。

 $string = 'Hi, https://example.com/logo.png,
     <a href="https://example.com/banner.png">https://example.com/banner.png</a>';

它使它看起来像:

Hi, <img src="https://example.com/logo.png" />,
     <a href="<img src="https://example.com/banner.png" />"><img src="https://example.com/banner.png" /></a>

这是我用来替换的:

return preg_replace_callback('/https?:'/'/(.*?)'.(jpg|png|gif)('?'w+='w+)?/i',    function($matches){ 
        return '<img src="'.$matches[0].'" />'; 
}, $string);

如何使它忽略锚标记。

谢谢。

不要直接使用正则表达式进行HTML操作。相反,您可以使用DOMDocument使用DOM操作。查找HTML字符串中的所有文本节点,并安全地将图像url替换为图像标签。

<?php
$string = 'Hi, https://example.com/logo.png,
<a href="https://example.com/banner.png">https://example.com/banner.png</a>';
$dom = new DOMDocument();
// This loads the HTML string in a special way to handle utf and 
// not append any extra HTML tags
$dom->loadHtml(mb_convert_encoding($string, 'HTML-ENTITIES', "UTF-8"), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// Get the text nodes
$xpath = new DOMXPath($dom);
foreach($xpath->query('//text()') as $node) {
    // Replace the text nodes with the replaced HTML fragments
    $replaced = preg_replace('/(https?:'/'/[^ ]+?(?:'.jpg|'.png|'.gif))/', '<img src="$1" alt="$1" />', $node->data);
    $frag = $dom->createDocumentFragment();
    $frag->appendXML($replaced);
    $node->parentNode->replaceChild($frag, $node);
}
echo $dom->saveHtml();
输出:

<p>Hi, <img src="https://example.com/logo.png" alt="https://example.com/logo.png">,
<a href="https://example.com/banner.png"><img src="https://example.com/banner.png" alt="https://example.com/banner.png"></a></p>

如果您也想排除锚点之间的图像url,您可以使用

$xpath->query('//text()[not(ancestor::a)]');
输出:

<p>Hi, <img src="https://example.com/logo.png" alt="https://example.com/logo.png">,
<a href="https://example.com/banner.png">https://example.com/banner.png</a></p>

我在演示中使用了这个正则表达式。请根据你的需要修改它。

preg_replace('/(https?:'/'/[^ ]+?(?:'.jpg|'.png|'.gif))/', '<img src="$1" alt="$1" />', $string);

初始尝试将使用negative look-behind and positive look-ahead来检查映像是否以"开始或以"结束。

$pattern = '/(?<!")https?:'/'/(.*?)'.(jpg|png|gif)(?!")('?'w+='w+)?/i';
return preg_replace_callback( $pattern, function( $matches ) { 
    return '<img src="'.$matches[0].'" />'; 
}, $string);