Help me with PHP regex [closed]
I want to remove the _8
from the $thumbnail
$thumbnail = "http://d2dsfsd.humbnails/20415/33-d148-45b1-9098-11e5c/thumbnail_8.jpg";
I must have been clear..
sometimes $thumbnail
might have _10
or _100
.. how do i handle then?
or to be a bit more flexible
$thumbnail = preg_replace('#_\d+(?=\.jpg$)#', '', $thumbnail);
(?=\.jpg$)
is a positive look ahead that ensures that after the _\d+
there is .jpg
and then the end of the string.
\d
is a digit
+
means one or more
$
matches the end of the string
Will it always be "_8"? If so just use:
$thumbnail = str_replace("_8.jpg", ".jpg", $thumbnail);
Or regex can be used to replace any series of numbers:
$thumbnail = preg_replace("#_[0-9]+\.jpg$#", ".jpg", $thumbnail);
Assuming no other underscores in the filename, you can do this:
$thumbnail = preg_replace('/_\d+/', '', $thumbnail);
fairly simple regex; removes underscore followed by any number of digits.
If you might have other occurrences of underscore followed by digits, and you only want to remove the one at the end, it gets a bit more complex, as you need to match the .jpg
but not remove it. You'd do something like this:
$thumbnail = preg_replace('/_\d+\.jpg$/', '.jpg', $thumbnail);
This removes the .jpg
as well as the underscore and digits, but then puts the .jpg
back again in the replacement string. Note, I've also added a $
to tie it to the end of the string to make double-sure it's matching the right part of the string, even if it's got other occurrences that match.
For variable integers, you can use:
$thumbnail = preg_replace( '~_([\d]+)\.jpg$~', ".jpg", $thumbnail );
This is fairly simple
$thumbnail = preg_replace('/_\d+\.jpg/', '.jpg', $thumbnail);
精彩评论