Remove non-numeric characters (except periods and commas) from a string

前端 未结 5 1930
一整个雨季
一整个雨季 2020-11-30 23:57

If I have the following values:

 $var1 = AR3,373.31

 $var2 = 12.322,11T

How can I create a new variable and set it to a copy of the data t

5条回答
  •  爱一瞬间的悲伤
    2020-12-01 00:27

    You could use filter_var to remove all illegal characters except digits, dot and the comma.

    • The FILTER_SANITIZE_NUMBER_FLOAT filter is used to remove all non-numeric character from the string.
    • FILTER_FLAG_ALLOW_FRACTION is allowing fraction separator " . "
    • The purpose of FILTER_FLAG_ALLOW_THOUSAND to get comma from the string.

    Code

    $var1 = '12.322,11T';
    
    echo filter_var($var1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
    

    Output

    12.322,11
    

    To read more about filter_var() and Sanitize filters

提交回复
热议问题