PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to reduce this 5 preg_replaces lines in 1 line?

 November 20, 2022     optimization, php, preg-replace     No comments   

Issue

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]);

Solution

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.



Answered By - Tim Biegeleisen
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing