Reputation: 607
examples:
this-is_a-random-filenam-jpg
this-is_a-random-filenam-png
this-is_a-random-filenam-gif
this-is_a-random-filenam-pdf
needed result:
this-is_a-random-filenam.jpg
this-is_a-random-filenam.png
this-is_a-random-filenam.gif
this-is_a-random-filenam.pdf
I came up with
\-(?=[^-]*$)
it just marks the last occurrence, doesn't check the condition that there is an actual valid file extension after it (jpeg,jpg,pdf,gif in my case) and doesn't work with "_".
Upvotes: 1
Views: 56
Reputation: 835
To perform this change by taking care of file extension, you can use this regex:
(-|_)(?=(?:jpe?g|png|gif|pdf)$)
And replace the matches with a .
.
You will have to list all file extensions you want in this pattern.
$re = '/(-|_)(?=(?:jpe?g|png|gif|pdf)$)/';
$str = 'this-is_a-random-filenam-jpg
this-is_a-random-filenam-png
this-is_a-random-filenam-gif
this-is_a-random-filenam-pdf';
$subst = '.';
$result = preg_replace($re, $subst, $str);
Upvotes: 1
Reputation: 176
use following flags at the end of your regular expression
/(-|_)(?=jpg|png|gif|pdf)/gm
Upvotes: 0