Extract a single integer from a string

后端 未结 21 2463
一个人的身影
一个人的身影 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-21 23:54
    $str = 'In My Cart : 11 12 items';
    preg_match_all('!\d+!', $str, $matches);
    print_r($matches);
    
    0 讨论(0)
  • 2020-11-21 23:54
    preg_replace('/[^0-9]/', '', $string);
    

    This should do better job!...

    0 讨论(0)
  • 2020-11-21 23:54

    try this,use preg_replace

    $string = "Hello! 123 test this? 456. done? 100%";
    $int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
    echo $int;
    

    DEMO

    0 讨论(0)
  • 2020-11-21 23:56

    For floating numbers,

    preg_match_all('!\d+\.?\d+!', $string ,$match);
    

    Thanks for pointing out the mistake. @mickmackusa

    0 讨论(0)
  • 2020-11-21 23:58

    for utf8 str:

    function unicodeStrDigits($str) {
        $arr = array();
        $sub = '';
        for ($i = 0; $i < strlen($str); $i++) { 
            if (is_numeric($str[$i])) {
                $sub .= $str[$i];
                continue;
            } else {
                if ($sub) {
                    array_push($arr, $sub);
                    $sub = '';
                }
            }
        }
    
        if ($sub) {
            array_push($arr, $sub); 
        }
    
        return $arr;
    }
    
    0 讨论(0)
  • 2020-11-22 00:01

    If you don't know which format the number is? int or floating, then use this :

    $string = '$125.22';
    
    $string2 = '$125';
    
    preg_match_all('/(\d+.?\d+)/',$string,$matches); // $matches[1] = 125.22
    
    preg_match_all('/(\d+.?\d+)/',$string2,$matches); // $matches[1] = 125
    
    0 讨论(0)
提交回复
热议问题