views:

62

answers:

3

I've a user form where I take a phone number as input in one of my fields. I have two seperate RegEx statements checking on the input.

First one is:

preg_match('/^([\(]{1}[0-9]{3}[\)]{1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?)?[0-9]{3}(\.|\-| )?[0-9]{4}$/', $phone);

and it works great. It can identify many different formats i.e. 222-333-4444 or 2224445555.

On the other hand when I try:

preg_replace('/\+?1?[-\s.]?\(?(\d{3})\)?[-\s.]?(\d{3})[-\s.]?(\d{4})/g', '($1) $2-$3', $phone);

which is supposed to format incoming string into (222) 333-4444 format, $phone is unchanged after the preg_replace() call.

Any help will be much appreciated!

+4  A: 

Just to make sure: You need to catch the return value, preg_replace doesn't modify the parameters directly:

$phone = preg_replace(..., $phone);
deceze
Ah the inconsistancies of php...
SeanJA
@deceze when I try this method $phone = preg_replace(pattern, replace, $phone) it's returning NULL which according to the PHP manual: "preg_replace() returns an array if the subject parameter is an array, or a string otherwise. If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred."So obviously there is something wrong with the way it's written in the script, but what?
Ben
A: 

Simplified the above, and came up with the following:

preg_replace( '/\b(\d{3})\D?(\d{3})\D?(\d{4})\b/' , '($1) $2-$3' , $inString );

Testing results:

preg_replace( '/\b(\d{3})\D?(\d{3})\D?(\d{4})\b/' , '($1) $2-$3' , '222-333-4444' );
# Returns '(222) 333-4444'

preg_replace( '/\b(\d{3})\D?(\d{3})\D?(\d{4})\b/' , '($1) $2-$3' , '2223334444' );
# Returns '(222) 333-4444'
Lucanos
I will give these a shot and see what happens. Thank you!
Ben
A: 

It was the /g causing the error in the pattern. Once I removed that it worked. Thanks everyone for trying!

Ben