0

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!

2
  • 1
    I'm not sure you want your $ values in the replace text this way. You have 4 capturing groups, you reference 3. Should not the last one be $4? Commented Oct 21, 2010 at 6:38
  • @bazmegakapa when I plug in this pattern shown in the preg_replace into gskinner.com/RegExr it works flawlessly. My problem is within the PHP script. I must be doing something wrong there. Commented Oct 21, 2010 at 15:10

3 Answers 3

9

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

$phone = preg_replace(..., $phone);
Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

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'

1 Comment

I will give these a shot and see what happens. Thank you!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.