开发者

Help me with PHP regex [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area开发者_开发百科, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜