Milos Cuculovic
Milos Cuculovic

Reputation: 20223

Regex to match one portion of a string

I have this types of strings:

aabbcc-12-00001-g001-1024.png

ddeeffgg-1-50001-i001-500.jpg

ddeeffgg-1-50001-i001.jpg

I would like to extract the filename without it's size, which is always the -xxx or -xxxx before the file extension.

For example, for the three strings, I would like to match:

aabbcc-12-00001-g001.png

ddeeffgg-1-50001-i001.jpg

ddeeffgg-1-50001-i001.jpg

My idea was to first march the size, then use preg_replace with PHP, but not sure how to only match the size, trying with:

-\d{3,4}\.[a-z]{3}

But this is matching -550.png or -1024.jpg etc.

Upvotes: 3

Views: 68

Answers (1)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

You can use preg_replace with a substitution:

$str = 'aabbcc-12-00001-g001-1024.png';
$result = preg_replace('/(-\d+)(.[A-Z]+)$/i', '$2', $str);
echo $result;

Upvotes: 5

Related Questions