Reputation: 606
how can I make a RegEx for remove everything from last underscore to .jpg extension in filenames?
E.g. I have
aosta_8b08e16ae42367d29cbf11bcf27f376a.jpg
aosta_madreperla_014cb17607a4fb23fcb94a8f26efb267.jpg
and need to change it to this
aosta.jpg
aosta_madreperla.jpg
Thank you
Upvotes: 0
Views: 70
Reputation: 46841
Remove the matched ones or replaced with empty string
_[^_]*(?=\.)
Pattern explanation:
_ '_'
[^_]* any character except: '_' (0 or more times)
(?= look ahead to see if there is:
\. '.'
) end of look-ahead
Read more about Lookahead and Lookbehind Zero-Length Assertions that do not consume characters in the string, but only assert whether a match is possible or not.
Upvotes: 3
Reputation: 27082
You don´t need to use regexp, use just substr
and strpos
, it should be faster.
$str = array(
'aosta_8b08e16ae42367d29cbf11bcf27f376a.jpg',
'aosta_madreperla_014cb17607a4fb23fcb94a8f26efb267.jpg'
);
foreach ($str as $s) {
echo substr($s, 0, strrpos($s, '_')) . substr($s, -4);
echo '<br>';
}
Upvotes: 0
Reputation: 67968
_(?!.*?_).*?(?=\.)
Try this.Replace by ``.See demo.
http://regex101.com/r/hQ1rP0/18
_
matches the character _ literally
(?!.*?_)
Negative Lookahead - Assert that it is impossible to match the a string containing _
.
(?=\.)
Positive Lookahead - Assert that the string ends when it has a .
ahead of it.
Upvotes: 0
Reputation: 59232
You can just do this using this regex
/[^_]+.jpg$/
and replace with .jpg
Upvotes: 0
Reputation: 174696
Regex:
^(.*)_[^.]*
Replacement string:
$1
Explanation:
^(.*)_
Captures all characters from the start upto the last _
symbol(excluding underscore) and store it into group 1.[^.]*
Matches any character but not of dot zero or more times.Upvotes: 0