如何从字符串中获取所有数字
问题描述:
我有一个字符串,看起来像abc,5,7
,我想从中获取数字。如何从字符串中获取所有数字
我想出这个:
^(?<prefix>[a-z]+)(,(?<num1>\d+?))?(,(?<num2>\d+?))?$#i
,但它只能与2号工作,我的字符串具有可变数量的数字。我不知道如何改变正则表达式来解决这个问题。请帮助
答
你可以试试这个
<?php
$string = "abc,5,7";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
?>
您也可以使用这个正则表达式!\d!
<?php
$string = "abc,5,7";
preg_match_all('!\d!', $string, $matches);
echo (int)implode('',$matches[0]);
答
explode
用逗号,
是最简单的方法。
,但如果你坚持用regexp
做这里是
$reg = '#,(\d+)#';
$text = 'abc,5,7,9';
preg_match_all($reg, $text, $m);
print_r($m[1]);
/* Output
Array
(
[0] => 5
[1] => 7
[2] => 9
)
*/
答
如何尝试。非常简单的应用的preg_replace( '/ [A-ZA-Z,] + /', '',$ STR); //从字符串中删除字母和逗号
<?php
$str="bab,4,6,74,3668,343";
$number = preg_replace('/[A-Za-z,]+/', '', $str);// removes alphabets from the string and comma
echo $number;// your expected output
?>
预期输出
46743668343
你不能试着用''爆炸,然后用'is_numeric()'条件在数值上迭代数组? – jitendrapurohit
如果开始时的前缀是必需的,请尝试使用'(?:^ [az] + | \ G(?!^)),\ K \ d +'[请参阅regex101上的演示文稿](https://regex101.com/r/yP5fT8/2)。否则使用'\ d +'。 –