I need regex to validate a number that could contain thousand seperators that would be one of three different characters (.
,
or ) or decimals that could be either
,
or .
. There are no max or min values, so that isn't a concern. If a decimal isn't in the number, it should be added. Once detected, I would then be able to process the resulting expressions into a set standard format.
Example values that would need to be detected (values on the left are what will be detected, values on the right will be the output we will code to, but displayed here for the benefit of better a understanding of my needs):
11,111.11
=> 11111.11
11'111.11
=> 11111.11
11 111.11
=> 11111.11
11.111,11
=> 11111.11
11'111,11
=> 11111.11
11 111,11
=> 11111.11
11,111
=> 11111.00
11'111
=> 11111.00
11 111
=> 11111.00
11.111
=> 11111.00
This is needed for a web site where the input values could be different based on different standard formats (depending on the end-user). In Switzerland, all those potential combinations may be used.
Help would be appreciated.
You may try the snippet below since I don't see how to achieve this using a singe regular expression.
$string = array("0,89", "11,111,111,111", "11,111.11", "11'111.11", "11 111.11", "11.111,11", "11'111,11", "11 111,11", "11,111", "11'111", "11 111", "11.111");
$pattern = "/^(\d{1,3}([,\s.']\d{3})*|\d+)([.,]\d+)?$/";
foreach($string as $price){
preg_match($pattern, $price, $matches);
echo $matches[0] , " -> " , preg_replace("/[,\s.']/", "", $matches[1]) , ((!empty($matches[3])) ? preg_replace("/[,\s.']/", ".", $matches[3]) : ".00") , "<br />";
}
Output:
0,89 -> 0.89
11,111,111,111 -> 11111111111.00
11,111.11 -> 11111.11
11'111.11 -> 11111.11
11 111.11 -> 11111.11
11.111,11 -> 11111.11
11'111,11 -> 11111.11
11 111,11 -> 11111.11
11,111 -> 11111.00
11'111 -> 11111.00
11 111 -> 11111.00
11.111 -> 11111.00
As you can see, in the first step, the pattern above will match any (valid) price format and place it into three groups. In the second step, the group (1) will be cleaned up of any separators while the separator in group (3) if exists, would be replaced with a dot (.) (and the zeros will be added if needed)
For more testings check the demo
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments