views:

37

answers:

1

I have this expression:

        $regex_phone = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})' 
                .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})' 
                .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
        if(!preg_match($regex_phone, $data['phone'])){ 
           $error[] = "Please enter a valid phone number."; 
        }else{ 
           $data['phone'] = preg_replace($regex_phone, '($1) $2-$3 ext.$4', $data['phone']);
        }

That will take a phone number such as: 803-888-8888 ext 2 as well as 803-888-8888

First number formats as: (803) 888-8888 ext.2 -- the desired effect

Second number formats as: (803) 888-8888 ext. -- blank extension

How can I set it so that if $4 is blank, that ext. won't show?

Thanks so much for any help you can offer. I hope this was clear.

+3  A: 

I'm not sure this fancy regex is really necessary
but lets see ...

Ahh, I modified the region around $4 in order
to allow for missing ext numbers. Can you spot the differences?

...
$regex_phone = 
  '/^
     (?:
       1(?:[. -])?
     )?
     (?: 
       \( (?=\d{3} \) ) # possible mistake? (probably correct)
     )?
     ([2-9]\d{2})       # $1
     (?:
       (?<=\(\d{3})\)
     )?
     \s?
     (?:
       (?<=\d{3})
       [.-]
     )?
     ([2-9]\d{2})       # $2
     [.\s-]?
     (\d{4})            # $3
     (?:
       \s? ext [.\s]? 
       (\d{1,5})?       # $4
     )?
 $/ix';

if( preg_match( $regex_phone, $data['phone'], $m) ) { 
   $data['phone'] = "$m[1] $m[2]-$m[3]" . (isset($m[4]) ? " ext.$m[4]" : '');
}
else { 
   $error[] = "Please enter a valid phone number.<br />"; 
}
...

Regards

rbo

rubber boots
Didn't even think about getting a preg_match variable. Worked like a charm. I modified a bit to fit my coding style, but the isset() and $m was what I needed. Thanks rbo
bradenkeith