-1

I belive minimal is better, so I'm wondering how could I reduce/optimize these 5 lines in 1 line?

#JPG
$post[message] = preg_replace('/<a href="(.+?)\.jpg" target="_blank">(.+?)<\/a>/', '<img src="$1.jpg">', $post[message]);

#JPEG
$post[message] = preg_replace('/<a href="(.+?)\.jpeg" target="_blank">(.+?)<\/a>/', '<img src="$1.jpeg">', $post[message]);

#GIF
$post[message] = preg_replace('/<a href="(.+?)\.gif" target="_blank">(.+?)<\/a>/', '<img src="$1.gif">', $post[message]);

#PNG
$post[message] = preg_replace('/<a href="(.+?)\.png" target="_blank">(.+?)<\/a>/', '<img src="$1.png">', $post[message]);

#BMP
$post[message] = preg_replace('/<a href="(.+?)\.bmp" target="_blank">(.+?)<\/a>/', '<img src="$1.bmp">', $post[message]);
1
  • 1
    what do you want to this?
    – Jerson
    Oct 26, 2020 at 1:06

1 Answer 1

3

Use an alternation:

$post[message] = preg_replace('/<a href="(.+?\.(?:jpe?g|gif|png|bmp))" target="_blank">.+?<\/a>/',
                              '<img src="$1">', $post[message]);

Note that I have removed the second capture group, which was the anchor text, as your regex replacement was not even using it.

1
  • Thank you very much Tim for your help and note. Your code works correctly and it's exactly what I was lookin for :)
    – Akirabyte
    Oct 26, 2020 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.