正则表达式 - 选择所有不带逗号的数字

时间:2017-07-28 03:53:45

标签: php regex numbers preg-replace

我一直试图仅捕获这句话中的数字,以便它保持如下:

在:

 - 602,135 results  

后:

602135

我正在测试以下内容:#\d+# 但只需选择我602

PS:我已经在其他帖子中咨询过,但他们无法解决我的问题。

3 个答案:

答案 0 :(得分:2)

您可以使用 preg_replace

试试这个

$str = '- 602,135 results';
echo $result = preg_replace("/[^0-9]/","",$str);

输出 602135

您也可以使用相同的输出: -

$result = preg_replace('/\D/', '', $str);

答案 1 :(得分:1)

\D+将会或等同于[^0-9]

只会返回数字。

请在此处查看:https://regex101.com/r/8CTgIm/1

[PHP]使用它:

$re = '/\D+/';
$str = '- 602,135 results  ';
$subst = '';

$result = preg_replace($re, $subst, $str); //602135

echo "The result of the substitution is ".$result;

答案 2 :(得分:0)

你不必为此使用正则表达式 不确定你实际上在这里没有使用正则表达式,但这里有一种替代方法。

$str = " - 602,135 results  ";

Echo str_replace("-", "", filter_var($str, FILTER_SANITIZE_NUMBER_INT));

它使用filter_var删除任何非数字且离开-602135的内容 然后我使用str_replace删除负号。

https://3v4l.org/iAVOB#output

相关问题