regex - Want a pattern for preg_match() for given input according to current situation... PHP -


if decimal separator ( point(.) or comma(,) , thousand separator (comma(,) or point(.)) present incoming value should handled pattern. current code

if (!preg_match('/^((?:(?:\-?[\d' . $thousandseparator . ']+(?:' . $decimalseparator . '\d+)?)|\s*))\s*(.*)$/', $value, $matches))  {    throw_error; } 

case 1 - $decimalseparator = '.'; $thousandseparator = ',';

allowed cases -

  • 45,789.45
  • 45,789.45 cm
  • 789 cm
  • 789.45 cm
  • 1,789 cm
  • 78,789,756.45

not allowed cases -

  • 45.789,78
  • 45.789,78 cm
  • 78.7.78,78
  • 7.8,5
  • 7.8 cm

case 2 - $decimalseparator = ','; $thousandseparator = '.';

allowed cases -

  • 45.789,78
  • 45.789,78 cm
  • 789,45
  • 1.789 cm
  • 789

not allowed cases -

  • 45,789.45
  • 45,789.45 cm
  • 789 cm
  • 789.45 cm
  • 1,789 cm
  • 78,789,756.45
  • 78,78,78 cm

note - 'cm' centimeter variable, there can inch, mm, km, etc. unit can present or not, if there, need handled. have put unit randomly, please not considered unit exact way.

thanks. :)

you can build pattern this:

$units = ['[mck]m', 'inch']; // complete $pattern = sprintf('~^-?\d{1,3}(?:[%s]\d{3})*(?:[%s]\d\d)?(?: (?:%s))?$~', $thousandsep, $decimalsep, implode('|', $units)); 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -