正则表达式 - Select 所有数字不带逗号
Regex - Select all numbers without commas
我一直试图只捕获这句话中的数字,以便它保持如下:
之前:
- 602,135 results
之后:
602135
我正在测试以下内容:#\d+#
但是只有 select 我 602
PS: 我已经在其他帖子中咨询过,但都没有解决我的问题。
您可以使用preg_replace
试试这个
$str = '- 602,135 results';
echo $result = preg_replace("/[^0-9]/","",$str);
输出- 602135
你也可以使用得到相同的输出:-
$result = preg_replace('/\D/', '', $str);
\D+
会做或相当于 [^0-9]
将只有 return 个数字。
看这里: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;
您不必为此使用正则表达式。
不确定在这里不使用正则表达式是否真的有所收获,但这是另一种方法。
$str = " - 602,135 results ";
Echo str_replace("-", "", filter_var($str, FILTER_SANITIZE_NUMBER_INT));
它使用 filter_var 删除任何非数字的东西,留下 -602135
。
然后我使用 str_replace 删除负号。
我一直试图只捕获这句话中的数字,以便它保持如下:
之前:
- 602,135 results
之后:
602135
我正在测试以下内容:#\d+#
但是只有 select 我 602
PS: 我已经在其他帖子中咨询过,但都没有解决我的问题。
您可以使用preg_replace
试试这个
$str = '- 602,135 results';
echo $result = preg_replace("/[^0-9]/","",$str);
输出- 602135
你也可以使用得到相同的输出:-
$result = preg_replace('/\D/', '', $str);
\D+
会做或相当于 [^0-9]
将只有 return 个数字。
看这里: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;
您不必为此使用正则表达式。
不确定在这里不使用正则表达式是否真的有所收获,但这是另一种方法。
$str = " - 602,135 results ";
Echo str_replace("-", "", filter_var($str, FILTER_SANITIZE_NUMBER_INT));
它使用 filter_var 删除任何非数字的东西,留下 -602135
。
然后我使用 str_replace 删除负号。