Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match lazy?

Hey guys I'm trying to strip out the last _1.jpg if it exists in my expression, but I am having some trouble

Scenarios are like follows.

image_name_1.jpg (should be image_name.jpg)

image_name_1_1.jpg (should be image_name_1.jpg)

I came up with this, but it seems to be returning null

$pic = ($pic[strlen]-6 == '_') ? preg_replace('/*.\_[0-9]/', '.jpg', $pic) : $pic;

What's wrong with my formula? Could someone help?

like image 947
ehime Avatar asked Dec 11 '25 22:12

ehime


2 Answers

*. makes here truble. You can use *.? - the ? mean lazy quantification.

But your expression havent to pattern whole input string, only target - see ohaal's answer.

like image 83
Honza Avatar answered Dec 14 '25 11:12

Honza


This should do it:

preg_replace('/_\d\.jpg$/', '.jpg', $pic);
like image 29
ohaal Avatar answered Dec 14 '25 11:12

ohaal



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!