Extract a single integer from a string

后端 未结 21 2466
一个人的身影
一个人的身影 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:16
    preg_match_all('!\d+!', $some_string, $matches);
    $string_of_numbers = implode(' ', $matches[0]);
    

    The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

    Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

    For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

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

    we can extract int from it like

    $string = 'In My Car_Price : 50660.00';
    
    echo intval(preg_replace('/[^0-9.]/','',$string));  # without number format   output: 50660
    echo number_format(intval(preg_replace('/[^0-9.]/','',$string)));  # with number format  output :50,660
    

    demo : http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398

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

    You can use following function:

    function extract_numbers($string)
    {
       preg_match_all('/([\d]+)/', $string, $match);
    
       return $match[0];
    }
    
    0 讨论(0)
提交回复
热议问题