大家好
如果字符串语法如下,我该如何从字符串中获取数字(正整数):
t_def_type_id_2
t_def_type_id_22
t_def_type_id_334
因此,在第一个字符串中,我想要获取1,在第二个字符串中,我想要获取22,在第三个字符串中,我想要获取334,使用preg_match_all或任何其他适合的php函数。
\d+$
使用preg_match
函数
\d+
。试试这个:
preg_match('/^\w+(\d+)$/U', $string, $match);
$value = (int) $match[1];
\w+
将首先吞掉整个字符串,然后每次向后退一位,直到满足正则表达式的其余部分。由于(\d+)
只需要匹配一个数字,所以它只能得到一个数字。 - Alan Moore您可以使用
str_replace('t_def_type_id_','');
以下是代码:
^[\d]+(\d+)$
preg_replace()
:$defTypeID = preg_replace("/^(.*?)(\d+)$/", "$2", $defTypeIDString);
$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
)
这是我的另一种解决方案。
$number = array_pop(explode('_', $string));
$num = ltrim(strrchr($string, "_"), "_");
你可以使用
^\w+(\d+)$
但我没有测试