-1

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
R_life_R
  • 786
  • 6
  • 26
  • Will all the strings(numbers) have 2 decimal and a separator before them? – Mikeyhun Sep 15 '19 at 09:42
  • 2
    Possible duplicate of [Remove all non-numeric characters from a string in PHP](https://stackoverflow.com/questions/53283229/remove-all-non-numeric-characters-from-a-string-in-php) – Jordan Lipana Sep 15 '19 at 10:03
  • this is not a duplicate. Need to handle decimals which is not the case in the proposed answer – R_life_R Sep 15 '19 at 11:56

1 Answers1

1

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.

Community
  • 1
  • 1
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35