常规exp从字符串中获取最后一个数字

时间:2011-03-29 14:08:19

标签: php regex

大家好 如果字符串语法如下,我如何从字符串中获取数字(正数):

  

t_def_type_id_2
t_def_type_id_22
t_def_type_id_334

所以,在第一个字符串中我想得到1,在第二个字符串中我想要得到22而在第三个字符串中我希望得到334使用preg_match_all或任何其他可用的php函数

10 个答案:

答案 0 :(得分:5)

您可以使用正则表达式

\d+$

preg_match

答案 1 :(得分:2)

如果字符串中只有一个数字,只需使用\d+

即可

答案 2 :(得分:2)

试试这个:

preg_match('/^\w+(\d+)$/U', $string, $match);
$value = (int) $match[1];

答案 3 :(得分:1)

您可以使用

str_replace('t_def_type_id_','');

答案 4 :(得分:1)

如下代码:

^ [\ d] +(\ d +)$

答案 5 :(得分:0)

您可以使用preg_replace()

$defTypeID = preg_replace("/^(.*?)(\d+)$/", "$2", $defTypeIDString);

答案 6 :(得分:0)

$string = "t_def_type_id_2
t_def_type_id_22
t_def_type_id_334"; 

preg_match_all("#t_def_type_id_([0-9]+)#is", $string, $matches);

$matches = $matches[1];
print_r($matches);

结果:

Array
(
    [0] => 2
    [1] => 22
    [2] => 334
)

答案 7 :(得分:0)

如果它始终是你的字符串中的最后一件事,那么使用平庸的字符串函数方法是可能的,看起来有点紧凑:

$num = ltrim(strrchr($string, "_"), "_");

答案 8 :(得分:0)

您可以使用

^\w+(\d+)$

但我没有测试

答案 9 :(得分:0)

这是我的替代解决方案。

$number = array_pop(explode('_', $string));
相关问题