how to clean/sanitize a number with different international formats in PHP?

i have different strings in PHP representing numbers. i am looking for a function to convert them to MYSQL compatible numbers ('4209.99'), regardeless of their international formatting.

    $test_number= "$4,209.99";
    $test_number= "$4209.99";
    $test_number= "$4209,99";
    $test_number= "4209,99";
    $test_number= "4209.99"; // the right format

1 answer

  • answered 2019-09-15 10:11 Markus Zeller

    Assuming you always have 2 decimal numbers, you could remove all non-digits and divide by 100.

    $nums = [
        "4209",
        "4209 EUR",
        "$4,209.99",
        "$4209.99",
        "$4209,99",
        "4209,99",
        "4209.99",
        "4209.00",
        "4209,00",
    ];
    
    foreach($nums as $num) {
        if(preg_match('/([\.\,]*)(\d{2})(\D*)$/', $num, $matches))
        {
            $num = preg_replace('/\D/', '', $num);
            if($matches[1]) $num /= 100;
        }
        echo $num, PHP_EOL;
    }
    

    4209

    4209

    4209.99

    4209.99

    4209.99

    4209.99

    4209.99

    4209

    4209

    Update Now it maches more test cases and divides by 100 only if a seperator is there.