tags:

views:

236

answers:

3

funtion declared as function ReformatePhoneNumber($number), whose argument will contain string data representing some phone number data(entered by the user). A valid phone number may consist of between 7 and 12 digits (0,9). Assume that in between some adjacent digits there may optionally appear either a single space. or a single hypen(-) any other phone number should be considered invalid.

if the phone number is valid the return value of your funtion should contain a string containing betwwen 7 and 12 digits, representing the same phone number after removing all hyphens and spaces. if the phone number is invalid, throw a standard PHP5 exception intialized with the text "Invalid phone number"

Eg: After calling ReformatPhoneNumber('012-345 69') the return value should be '01234569'

+1  A: 

Start Here

Use regex to strip anything that you don't want.

That is the standard method.

http://php.net/manual/en/function.preg-replace.php

Laykes
A: 

I'd use str_replace to make it easy, or a regex if I was feeling brave.

Rich Bradshaw
A: 
function ReformatPhoneNumber($number)
{
    $iPhoneLen = strlen($number);
    try
    {
        if($iPhoneLen <7 || $iPhoneLen > 12)
        {
            throw new Exception('Invalid phone number');
        }
        else if((preg_match("/^[0-9][0-9\s-]+[0-9]$/",$number)))
        {
            if(!(preg_match("/[-s]+-|[-]+\s|[-]+-|[\s]+\s/",$number)))
            {
                echo preg_replace("/(\D)/",'',$number);
            }
            else
            {
                throw new Exception('Invalid phone number');
            }

        }
        else
        {
            throw new Exception('Invalid phone number');
        }
    }
    catch (Exception $e) 
    {
         echo $e->getMessage();
    }
}
Sanjhon