如何只从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:13:08  来源:igfitidea点击:

How Do I Take Out Only Numbers From A PHP String?

phpstringnumbers

提问by mehulmpt

Suppose, I have this string:

假设,我有这个字符串:

$string = "Hello! 123 How Are You? 456";

I want to set variable $intto $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]);

enter image description here

在此处输入图片说明

回答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 是每个数字(不是数字!,也包括负值!)的加载位置,可用于不同的更多操作。