PHP regular expression - filter number only

后端 未结 6 651
南旧
南旧 2020-11-30 04:46

I know this might sound as really dummy question, but I\'m trying to ensure that the provided string is of a number / decimal format to use it later on with PHP\'s number_fo

相关标签:
6条回答
  • 2020-11-30 04:53

    To remove anything that is not a number:

    $output = preg_replace('/[^0-9]/', '', $input);
    

    Explanation:

    • [0-9] matches any number between 0 and 9 inclusively.
    • ^ negates a [] pattern.
    • So, [^0-9] matches anything that is not a number, and since we're using preg_replace, they will be replaced by nothing '' (second argument of preg_replace).
    0 讨论(0)
  • 2020-11-30 04:57

    Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:

    $output = preg_replace( '/[^0-9]/', '', $string );
    
    0 讨论(0)
  • 2020-11-30 04:57

    use built in php function is_numeric to check if the value is numeric.

    0 讨论(0)
  • 2020-11-30 05:04

    You can try that one:

    $string = preg_replace('/[^0-9]/', '', $string);
    

    Cheers.

    0 讨论(0)
  • 2020-11-30 05:04

    Another way to get only the numbers in a regex string is as shown below:

    $output = preg_replace("/\D+/", "", $input);
    
    0 讨论(0)
  • 2020-11-30 05:08

    You could do something like this if you want only whole numbers.

    function make_whole($v){
        $v = floor($v);
        if(is_numeric($v)){
          echo (int)$v;
          // if you want only positive whole numbers
          //echo (int)$v = abs($v);
        }
    }
    
    0 讨论(0)
提交回复
热议问题