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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.