Jump to content

Regex help


dpacmittal

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.