I've a user form where I take a phone number as input in one of 开发者_StackOverflow社区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!
Just to make sure: You need to catch the return value, preg_replace
doesn't modify the parameters directly:
$phone = preg_replace(..., $phone);
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'
It was the /g causing the error in the pattern. Once I removed that it worked. Thanks everyone for trying!
精彩评论