从字符串中获取最后一位数字

时间:2012-10-12 09:09:36

标签: php regex

我有这个字符串:tag:domain.com,2012-10-12:feed / channel / id / 335

我试图将此字符串中的最后一位数字转换为变量。此字符串中的日期也是动态的,但我不需要在变量中。

这是我的代码:

$string = "tag:domain.com,2012-10-12:feed/channel/id/335";

preg_match('/tag\:domain\.com,|\d+|-|\d+|-|\d+|\:feed\/channel\/id\/|\d+/', $string, $matches);


$last_digits = ???    

也许有一种更简单的方法可以做到这一点?

4 个答案:

答案 0 :(得分:6)

这应该有用。

$aParts = explode('/', $string);
$iId = end($aParts);

答案 1 :(得分:0)

是的。使用锚点作为字符串的结尾:

preg_match('/\d+$/', $string, $matches);

$表示字符串的结尾,或多行模式中的行的结尾)

然后你可以像这样检索ID:

$last_digits = $matches[0];

答案 2 :(得分:0)

preg_match('/(\d+)$/', $string, $matches);

$ - 表示结束

$ matches [1]会有你的价值

答案 3 :(得分:0)

这应该有效:

$string = "tag:domain.com,2012-10-12:feed/channel/id/335";
$pattern = "/\/(\d+)$/";
preg_match($pattern, $string, $matches);

$number = $matches[1];

基本上,您要求/和字符串$之间的任何数字。

相关问题