Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP use regex to convert uppercase file extention to lowercase

Tags:

regex

php

I am trying to achieve the following conversion:

IM22_htp.JPG -> IM22_htp.jpg

So far I have tried the following but it doesn't seem to work:

$string = "IM22_htp.JPG";
$pattern = '/(.+) \.(\w+)/i';
$replacement = '${1}\. strtolower($3)';
echo preg_replace($pattern, $replacement, $string);
like image 647
RazorHead Avatar asked Jan 18 '26 07:01

RazorHead


1 Answers

Using regex:

$string = "IM22_htp.JPG";
$new_string = preg_replace_callback('/\.\w+$/', function($m){
   return strtolower($m[0]);
}, $string);
echo $new_string;

Using pathinfo():

$string = "IM22_htp.JPG";
$new_string = pathinfo($string, PATHINFO_FILENAME) . '.' . strtolower(pathinfo($string, PATHINFO_EXTENSION));
echo $new_string;
like image 192
HamZa Avatar answered Jan 19 '26 21:01

HamZa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!