-3

I'm looking for solution to change all img tags where is src imgur. I have try this and generaly this is working, but problem can be if imgur change their subdomain in this case this regex wont work.

So to be more clear i just need to add class name too all images hosted on imgur.

$string = 'I have been searching <img src="https://i.imgur.com/NknpNdu.jpg" alt=""> for...';
$regex = '#<img src="https://i.imgur.com([^"/]*/?[^".]*\.[^"]*)"([^>]*)>#';
$replace = '<img class="newClass" src="https://i.imgur.com/$1">';
$Content = preg_replace($regex, $replace, $string);
hadal
  • 1
  • 2

1 Answers1

0

My guess is that this expression

(<img src=".*?imgur\.com(.*?))(?=\/?\s?>)

with a replacement of $1 class="newClass" might just work OK.

Demo 1

Test

$re = '/(<img src=".*?imgur\.com(.*?))(?=\/?\s?>)/s';
$str = 'I have been searching <img src="https://i.imgur.com/NknpNdu.jpg" alt=""> for... I have been searching <img src="https://i.imgur.com/NknpNdu.jpg" alt=""> for... I have been searching <img src="https://i.imgur.com/NknpNdu.jpg" alt=""> for... I have been searching <img src="https://i.imgur.com/NknpNdu.jpg" alt="" /> for... ';
$subst = '$1 class="newClass"';

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

echo $result;

Or more simplified, with less boundaries, this expression:

(<img .*?imgur\.com(.*?))(?=\/?\s?>)

would do the same.

Demo 2

Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69