鉴于此,任何人都知道如何使用 preg_match 获取最后一位数字:
图像/列表/列表_id_15_4.png或者
图片/listings/listings_id_15_4.jpg
扩展名可能不同,我只需要找到 ' 之前的最后一个数字。'
从这两个字符串中,我只需要 '4'
你可以使用$
它,这意味着[在字符串的末尾]
您从获得扩展的部分开始:
\.[a-zA-Z]$ // this will match '.png' and '.jpg'
// Or alternatively
\.\w{2,4}$ // this will match '.png' and '.jpg', 2 till 4 chars long
然后你想得到它前面的数字,所以从后面展开它:
([0-9]+)\.[a-zA-Z]+$ // this will also select the number in front of it
现在还选择其余的,而不将其放在一个组中(扩展也是如此):
.*?([0-9]+)\.[a-zA-Z]+$ // this will select the whole thing, but only the number you want is in a group
使用该正则表达式,您可以在代码中使用该组,例如\\1
或$1
/\d(?=\.\w+$)/
This matches a digit, that is followed by a dot and one or more word characters (which is what I figure an extension to be).
Add a +
after the \d
if you want a full number instead of a single digit.