PHP remove commas from numeric strings

前端 未结 7 1437
悲哀的现实
悲哀的现实 2020-11-30 12:21

In PHP, I have an array of variables that are ALL strings. Some of the values stored are numeric strings with commas.

What I need:

A way to trim the comma

相关标签:
7条回答
  • 2020-11-30 12:38

    Do it the other way around:

    $a = "1,435";
    $b = str_replace( ',', '', $a );
    
    if( is_numeric( $b ) ) {
        $a = $b;
    }
    
    0 讨论(0)
  • 2020-11-30 12:40

    Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)

    0 讨论(0)
  • 2020-11-30 12:40

    Try this .this worked for me

    number_format(1235.369,2,'.','')

    if you use number_format like this number_format(1235.369,2) answer will be 1,235.37

    but if you use like below

    number_format(1235.369,2,'.','') answer will be 1235.37

    it's removing the "," of "1,235.37"

    0 讨论(0)
  • 2020-11-30 12:44

    It sounds like the ideal solution for what you're looking for is filter_var():

    $a = filter_var($a, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
    

    (Note that it's using FILTER_VALIDATE_FLOAT instead of FILTER_VALIDATE_INT because that one doesn't currently have a FILTER_FLAG_ALLOW_THOUSAND option).

    0 讨论(0)
  • 2020-11-30 12:56

    If you want to remove commas from numbers inside a string that also contains words, the easiest way I think would be to use preg_replace_callback:

    Example:  

    $str = "Hey hello, I've got 12,500 kudos for you, spend it well"

    function cleannr($matches)
    {
        return str_replace("," , "" , $matches["nrs"]);
    }
    
    $str = preg_replace_callback ("/(?P<nrs>[0-9]+,[0-9]+)/" , "cleannr" , $str);
    


    Output:

    "Hey hello, I've got 12500 kudos for you, spend it well"


    In this case the pattern (regex) differs from the one given in the accepted answer since we don't want to remove the other commas (punctuation).

    If we'd use /[0-9,]+/ here instead of /[0-9]+,[0-9]+/ the output would be:

    "Hey hello I've got 12500 kudos for you spend it well"

    0 讨论(0)
  • 2020-11-30 12:58

    The easiest would be:

    $var = intval(preg_replace('/[^\d.]/', '', $var));
    

    or if you need float:

    $var = floatval(preg_replace('/[^\d.]/', '', $var));
    
    0 讨论(0)
提交回复
热议问题