RSS | Archive | Random | E-mail

About

Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.

Links

Codepuzzling main site
Development site
ByteStrike italian blog
Follow me on Twitter

My Life Style

while(passion) {
  try {
    myLife.run();
  }catch(LifeExceptions) {  
    stronger++;
    continue;
   }
}

Following

5 June 09

[PHP] How to test if a string is a number (with localization issues)

If you use is_numeric function, you could note that 45,362.00 or 45.362,00 are not numbers for this function (only one dot is permitted). So here it is a function (taken from this comment) that uses regular expression to extend is_numeric functionality:

function my_is_numeric($value)  {
    $american = preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
    $world = preg_match ("/^(-){0,1}([0-9]+)(.[0-9][0-9][0-9])*([,][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
   return ($american or $world);
}

$numbers = array("72", "15.3", "45,362.00", "45.362,00", "62.3692,00", "15:15:00", "15,3");
foreach($numbers as $val) 
	echo "$val is numeric? D: ".is_numeric($val)." M:".my_is_numeric($val)."
";
…and the result is:
72 is numeric? D: 1 M:1
15.3 is numeric? D: 1 M:1
45,362.00 is numeric? D: M:1
45.362,00 is numeric? D: M:1
62.3692,00 is numeric? D: M:
15:15:00 is numeric? D: M:
15,3 is numeric? D: M:1

Tags: php regexp
Comments (View)
blog comments powered by Disqus
Themed by Hunson. Originally by Josh