For one thing, you have a syntax error:
public string $phoneFormats = array(
'gb' => "xxxxx xxxxxx",
'us' => "xxx-xxx-xxxx"
// etc etc etc
);
Change it to:
public $phoneFormats = array(
'gb' => "xxxxx xxxxxx",
'us' => "xxx-xxx-xxxx"
// etc etc etc
);
Next, what you are asking can be pretty complicated and would require a decent amount of research into valid phone numbers. For a human to say "it should start with a and then be followed by a , , , or __" is a lot easier than it is for a computer, and for you to do this for more than a few countries will take a significant amount of work.
Keep in mind also that an invalid phone number is not the end of the world for most applications. It just means that you can't call that person, which is probably something they don't want you to do anyway if they're just registering on your site.
However, if you are really bent on this, you're going to need to use regular expressions. Try this:
class condition extends utilities
{
public $phoneFormats = array(
/* This regular expression should be used with preg_ functions
and it will match "0 followed by 1, 2, 5, or 7, followed by 9 digits" */
'gb' => "/^
(
0{1}
[1257]{1}
[0-9]{9}
)
\$/x",
/* This regex will match phone numbers in the format
"1 followed by 10 digits" or "10 digits" */
'us' => "/^
(
(
[0-9]{10}
)
|
(
1{1}[0-9]{10}
)
)
\$/x"
);
// Remove all symbols from a string including &,
public static function RemoveSpecialChars($str)
{
// This is bad style! This many functions should never be on one line!
return strtolower(trim(stripslashes(preg_replace('/[^\w\d\s-\/,.&]+/i', '', strip_tags($str)))));
}
/* Removes all spaces from $str
Handy for crdit card numbers */
public static function RemoveSpaces ($str)
{
return str_replace(" ", "", ereg_replace('[-[:space:]]', '',trim($str)));
}
public static function ValidatePhoneNumber($phone, $country = "gb")
{
// First, let's presume that the phone number is valid.
$returnVal = true;
// Find required format for phone number
$format = self::$phoneFormats[$country];
/* The correct number of digits is implied by the regex's
so there's no need to check them */
/* Next, condition phone number into it's numerical format without spaces or hyphens
or any other special chars */
$phone = self::RemoveSpaces($phone);
$phone = self::RemoveSpecialChars($phone);
$returnVal = preg_match($phone, $format);
return $returnVal;
}
} // End class condition