如何从字符串中提取所有数字

How to pick up all numbers from string

我有一个看起来像 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