Jump to content

Recommended Posts

First of all, sorry for not being able to provide a more appropriate title.

 

Write a function declared as function ReformatPhoneNumber($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 hyphen (-). Any other phone number should be considered invalid.

 

If the phone number is valid, the return value of your function should contain a string containing between 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 initialized with the text "Invalid phone number".

 

The first and the last character of the string should be a number.

 

For example, after calling ReformatPhoneNumber('012-345 69') the return value should be '01234569'. Calling the function with any of these values: '012345', '-012345 678', '01203- 34566', '123456678875432', '1234x567' should result in an exception.

This is a question from elance coding test. I completed it last time by using all sorts of functions and a very basic regex. This time I tried to become brave and thought of solving it completely using Regexes. However I got stuck at multiple points (hence, the inappropriate title).

 

I tried these which are obviously wrong:

if(preg_match('!^\d([\d]+(\s|\-)?){5,10}\d$!',$number))

I know it would accept any length of string.

if(preg_match('!^\d(\d|\s|\-){5,10}\d$!',$number))

This would allow multiple spaces and hyphens next to each other.

 

Normally, my knowledge on regex usually gets me through my work and I don't usually need help in this regard. However, this one completely got me.

Any help would be appreciated.

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/201358-regex-help/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.