0

I wish to replace all src attributes of img tags in a string.

My string:

$string = "some text with <img src='/uploads/images/5d0554.jpeg'> and 
<img src='/uploads/images/507a.jpeg'> or <img src='/uploads/images/0a74.jpeg'> in it.";

should become:

$string = "some text with <img src='some/value/one.jpeg'> and 
<img src='alue/SomethingElse.png'> or <img src='Value3'> in it.";

What I tried to do:

$regex = '/< *img[^>]*src *= *["\']?([^"\']*)/i';

preg_match_all($regex, $string, $matches);
$srcMatches = $matches[1];

$replacementValues = ["some/value/one.jpeg", "value/SomethingElse.png", "Value3"];

preg_replace_callback($regex, function($matches) use (&$replacementValues) {
    return array_shift($replacementValues);
}, $string);

This gives me

some long text with some/value/one.jpeg'> and 
value/SomethingElse.png'> or Value3'> in it.

I also tried with preg_replace, but that gave me issues because of all the /'s in the values to be replaced.

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/a/1732454/1839439) – Dharman Jun 15 '19 at 22:31
  • 1
    There is also an option to use domdocument and load the string as html with for example a wrapper to access it by id. Then you can replace the image names and get back the html. See https://3v4l.org/NL950 – The fourth bird Jun 16 '19 at 11:09

1 Answers1

0

This expression would likely do the replacements using 6 capturing groups:

$re = '/([\s\S]*?)(src=[\'"])\/uploads\/images\/.+?(\..+?)([\'"]>[\s\S]*?src=[\'"])\/uploads\/images\/.+?\..+?([\'"]>[\s\S]*?src=[\'"])\/uploads\/images\/.+?\..+?([\'"]>[\s\S]*)/m';
$str = 'some text with <img src=\'/uploads/images/5d0554.jpeg\'> and 
<img src=\'/uploads/images/507a.jpeg\'> or <img src=\'/uploads/images/0a74.jpeg\'> in it.';
$subst = '$1$2some/value/one$3$4alue/SomethingElse\\.png$5Value3$6';

$result = preg_replace($re, $subst, $str);

echo $result;

Output

some text with <img src='some/value/one.jpeg'> and 
<img src='alue/SomethingElse.png'> or <img src='Value3'> in it.

Demo

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
  • The problem with this solution is that it is not reusable enough. My regex should capture all kinds of urls within `scr="..."`, and also the replacement values can be very different. – Dirk J. Faber Jun 15 '19 at 22:29
  • Because I only want to target the `src` attributes of `img` elements. And no, they can be very different unfortunately. – Dirk J. Faber Jun 15 '19 at 22:35