for example we have string like this :- $str = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.
so then we can do replace img tag like below
STEP 1
$str = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.';
if(preg_match("/(<img .*>)/i", $str)){
$img_array = preg_split('/(<img .*>)/i', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
}
This will output:
array(5) {
[0]=>
string(5) "Text "
[1]=>
string(22) "<img src="hello.png" >"
[2]=>
string(7) " hello "
[3]=>
string(21) "<img src="bye.png" />"
[4]=>
string(12) " other text."
}
STEP 2 then we will to do replace in for loop
for ($i = 0; $i < count($img_array); $i++){
$url = "welcome.png";
$img_array[$i] = preg_replace('/(<img .*>)/i', '<img src="'.$url.'" alt="'.$url.'">', $img_array[$i]); //replace src path & alt text
}
STEP 3 then after convert array to string
$str = implode('', $img_array);
then after you will get final output like this
$str = 'Text <img src="welcome.png" > hello <img src="welcome.png" /> other text.';