Arts Arts - 29 days ago 10
PHP Question

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

How can I replace strings between tags like

<img src="xxxx">
inside a string?

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


I need to modify the contents of the tag
<img src="www.google.jpg"/>
to
<img src="www.myImages.jpg"/>
.

Desired output:

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

Answer

I realize there is already an answer related to using the DOM. Without doing so, you can accomplish what you're needing but with 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);

Output:

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