PHP remove commas from numeric strings

前端 未结 7 1465
悲哀的现实
悲哀的现实 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: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[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"

提交回复
热议问题