Extract a single integer from a string

后端 未结 21 2499
一个人的身影
一个人的身影 2020-11-21 23:33

I want to extract the digits from a string that contains numbers and letters like:

"In My Cart : 11 items"

I want to extract the nu

相关标签:
21条回答
  • 2020-11-22 00:09

    I do not own the credit for this, but I just have to share it. This regex will get numbers from a string, including decimal points/places, as well as commas:

    /((?:[0-9]+,)*[0-9]+(?:\.[0-9]+)?)/

    Cited from here:
    php - regex - how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01)?

    0 讨论(0)
  • 2020-11-22 00:09

    Depending on your use case, this might also be an option:

    $str = 'In My Cart : 11 items';
    $num = '';
    
    for ($i = 0; $i < strlen($str); $i++) {
    
        if (is_numeric($str[$i])) {
            $num .= $str[$i];
        }
    }
    
    echo $num; // 11
    

    Though I'd agree a regex or filter_var() would be more useful in the stated case.

    0 讨论(0)
  • 2020-11-22 00:10

    Follow this step it will convert string to number

    $value = '$0025.123';
    $onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    settype($onlyNumeric,"float");
    
    $result=($onlyNumeric+100);
    echo $result;
    

    Another way to do it :

    $res = preg_replace("/[^0-9.]/", "", "$15645623.095605659");
    
    0 讨论(0)
  • 2020-11-22 00:12

    Using preg_replace:

    $str = '(111) 111-1111';
    $str = preg_replace('/\D/', '', $str);
    echo $str;
    

    Output: 1111111111

    0 讨论(0)
  • 2020-11-22 00:12

    Since there is only 1 numeric value to isolate in your string, I would endorse and personally use filter_var() with FILTER_SANITIZE_NUMBER_INT.

    echo filter_var($string, FILTER_SANITIZE_NUMBER_INT);
    

    A whackier technique which works because there is only 1 numeric value AND the only characters that come before the integer are alphanumeric, colon, or spaces is to use ltrim() with a character mask then cast the remaining string as an integer.

    Demo

    $string = "In My Cart : 11 items";
    echo (int)ltrim($string, 'A..z: ');
    // 11
    

    If for some reason there was more than one integer value and you wanted to grab the first one, then regex would be a direct technique.

    Demo

    echo preg_match('/\d+/', $string, $m) ? $m[0] : '';
    
    0 讨论(0)
  • 2020-11-22 00:13

    You can use preg_match:

    $s = "In My Cart : 11 items";
    preg_match("|\d+|", $s, $m);
    var_dump($m);
    
    0 讨论(0)
提交回复
热议问题