Php:当使用正则表达式在 html 中存在多个 img 标签时,如何用不同的内容替换 src


Php: How to replace src with different different content when multiple img tag exists in html using regex

我从ckeditor获取html内容,我有以下html内容

<p><strong>Hello</strong></p>
<p><img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABVYAAAMACAIAA" style="height:131px; width:234px" /></p>
<p><strong>How are you</strong></p>
<p><img alt="" src="data:image/png;base64,ABAXKuVAAAAA3NCSVQICAjb4U/gAAAgAElEQV" style="height:142px; width:253px" /></p>
<p><strong>Good Morning</strong></p>
<p>&nbsp;</p>

现在我想用不同的图像名称替换每个图像标签src。让我们举例说

<p><strong>Hello</strong></p>
<p><img alt="" src="img.jpg" style="height:131px; width:234px" /></p>
<p><strong>How are you</strong></p>
<p><img alt="" src="test.jpg" style="height:142px; width:253px" /></p>
<p><strong>Good Morning</strong></p>
<p>&nbsp;</p>

图像源是动态绑定的。所以它可以是任何东西。替换后,我将此 HTML 内容保存到数据库中。

我已经完成了

$image_name ='<p><strong>Hello</strong></p>
    <p><img alt="" src="img.jpg" style="height:131px; width:234px" /></p>
    <p><strong>How are you</strong></p>
    <p><img alt="" src="test.jpg" style="height:142px; width:253px" /></p>
    <p><strong>Good Morning</strong></p>
    <p>&nbsp;</p>';
    $html = preg_replace('!(?<=src'='").+(?='"('s|'/'>))!', 'img.jpg',$image_name );

但这取代了所有相同的 src。

我希望整个内容相同,除了<img>标签src。我需要使用正则表达式替换此内容。我更喜欢正则表达式,因为我想将此替换的 html 保存到数据库中。如果任何其他解决方案有效,那也很好。

我已经使用 DOM 解析器作为评论中给出的建议。以下是我的

$image_name = '<p><strong>Hello</strong></p>
<p><img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABVYAAAMACAIAA" style="height:131px; width:234px" /></p>
<p><strong>How are you</strong></p>
<p><img alt="" src="data:image/png;base64,ABAXKuVAAAAA3NCSVQICAjb4U/gAAAgAElEQV" style="height:142px; width:253px" /></p>
<p><strong>Good Morning</strong></p>
<p>&nbsp;</p>';
$doc = new DOMDocument();
$doc->loadHTML($image_name);
$img_tags = $doc->getElementsByTagName('img');
$i=0;
foreach ($img_tags as $t )
{
    $savepath = 'img_'.$i.'jpg';
    $t->setAttribute('src',$savepath);
    $i++;
}
$cont = $doc->saveHTML();

这给了我适当的结果。