如何只从 PHP 字符串中取出数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22728254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Do I Take Out Only Numbers From A PHP String?
提问by mehulmpt
Suppose, I have this string:
假设,我有这个字符串:
$string = "Hello! 123 How Are You? 456";
I want to set variable $int
to $int = 123456;
我想将变量设置$int
为$int = 123456;
How do I do it?
我该怎么做?
Example 2:
示例 2:
$string = "12,456";
Required:
必需的:
$num = 12456;
Thank you!
谢谢!
回答by I?ya Bursov
Correct variant will be:
正确的变体将是:
$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
回答by Fopa Léon Constantin
You can use this method to select only digit present in your text
您可以使用此方法仅选择文本中存在的数字
function returnDecimal($text) {
$tmp = "";
for($text as $key => $val) {
if($val >= 0 && $val <= 9){
$tmp .= $val
}
}
return $tmp;
}
回答by Shankar Damodaran
Use this regular expression !\d!
使用这个正则表达式 !\d!
<?php
$string = "Hello! 123 How Are You? 456";
preg_match_all('!\d!', $string, $matches);
echo (int)implode('',$matches[0]);
回答by Miroslav Gorchev
You can use the below:
您可以使用以下内容:
$array = [];
preg_match_all('/-?\d+(?:\.\d+)?+/', $string, $array);
Where $string is the entered string and $array is where each number(not digit!,including also negative values!) is loaded and available for different more operations.
$string 是输入的字符串,$array 是每个数字(不是数字!,也包括负值!)的加载位置,可用于不同的更多操作。