如何替换 PHP 中标签 <img src="example.com"/> 之间的字符串?

How can i replace string beetwen tags <img src="example.com"/> in PHP?

如何替换标签之间的字符串,例如字符串中的 <img src="xxxx">

$string ="<h1> hi, My name is Bob</h1><img src="www.ewrfcds.jpg"/> this is my pictures <img src="www.google.jpg"/>";

我需要将标签<img src="www.google.jpg"/>的内容修改为<img src="www.myImages.jpg"/>

期望的输出:

$string ="<h1> hi, My name is Bob</h1><img src="www.myImages1.jpg"/> this is my pictures <img src="www.myImages2.jpg"/>";

我建议您使用 DOM 而不是正则表达式。由于替换涉及多个不同的图像源,因此解决方案取决于您要如何指定要用哪个图像替换哪个图像。下面的代码将替换基于 URL 数组的图像源。字符串中的第一个图像将获得数组的第一个源,依此类推。

<?php

$string     = '<h1> hi, My name is Bob</h1><img src="www.ewrfcds.jpg"/> this is my pictures <img src="www.google.jpg"/>';
$imgUrls    = array('www.myImages1.jpg', 'www.myImages2.jpg');
$doc        = new DOMDocument();
$i          = 0;

$doc->loadHTML($string);
$images = $doc->getElementsByTagName('img');

foreach($images as $image) {

    $image->setAttribute('src', $imgUrls[$i]);
    $i++;
}

$newString  = $doc->saveHTML();

echo $newString;

?>

输出:

<h1> hi, My name is Bob</h1><img src="www.myImages1.jpg"> this is my pictures <img src="www.myImages2.jpg">

我知道已经有一个与使用 DOM 有关的答案。如果不这样做,您可以完成您需要的,但使用 PHP.

$string = '<h1> hi, My name is Bob</h1><img src="www.ewrfcds.jpg"/> this is my pictures <img src="www.google.jpg"/>';

// Get all the matches from the string
preg_match_all('/<img src="(.*?)"\/>/', $string, $matches);

// Create the regex pattern for each match
foreach($matches[1] as $match) {
    $patterns[] = '/' . $match . '/';
}

// Set the replacements
$replacements = array('www.myImages1.jpg', 'www.myImages2.jpg');

echo preg_replace($patterns, $replacements, $string);

输出:

<h1> hi, My name is Bob</h1><img src="www.myImages1.jpg"/> this is my pictures <img src="www.myImages2.jpg"/>