views:

105

answers:

4

Hello,

i'm new to regex, and i only need one statement.

I want that my statement accepts these numbertyps:

06643823423 could be longer or 0664 3843455 or +43664 4356999

and it's important that these is only one statement.

can anyone help me?

thanks mike

A: 

How about:

^\+?[0-9 ]+$

You can use that with preg_match, e.g.

$matches = preg_match("/^\+?[0-9 ]+$/", $telephone_number);
Bobby Jack
+1  A: 
$regExp = '/^([+][4][3]|[0]){1}([0-9]{3})([ ]{0,1})([0-9]{7})$/';
$number = "06643823423";

if(!preg_match($regExp,trim($number)))
{
        echo FALSE;
}
else
{                
        echo TRUE;
}
Maulik Vora
This (`([+][4][3]|[0]){1}`) hurts my eyes. `(\+43|0)` does the exact same ... and is less confusing, IMO.
jensgram
Thanks :) I had used this regEx before 1 month , at that time It is not worked as expected , so I am using like this. now I will use as you suggested
Maulik Vora
also, you cant echo false or true haha, there booleans.
RobertPitt
@RobertPitt, you can echo booleans, but it's not pretty. True prints as '1', and False prints as ''.
Rocket
yea you cant echo false is what i meant, why would you want to echo a boolean anyway ?
RobertPitt
@RobertPitt Its just an example , you can do whatever you want to do there. you can return true or false or can do any further process. It was jus texample, haha.
Maulik Vora
A: 

out ofwhat you have there, the only regex I could come up with is:

$phone_number = '+449287645367';
var_dump(preg_match("/^[\+|0][0-9]{10,12}$/",str_replace(' ','',$phone_number)));
RobertPitt
jensgram, that was not an error mate, it tests for only the + because it can be +[0-9]{12} as well as 0[0-9]{10} the 12 length is to accommodate the +*44*
RobertPitt
So you mean `(\+|0)`, I guess. `[+|0]` means `+` or `|` or `0` AFAIK (I may be wrong, though).
jensgram
No your right, for some reason he online PHP tester I used to to test this strips backslashes so after I copied the working regex it had removed the slash :/
RobertPitt
A: 

Try \+?\d+\s?\d+

To explain:
\+? - a plus sign (escaped with \, since '+' is a special character in regex). The '?' means '0 or 1 of the preceding characters' making it optional
\d+ - \d means a digit; the plus sign means 1 or more
\s? - \s means a white space character; the ? makes it optional
\d+ - \d means a digit; the plus sign means 1 or more

So this should match 2 or more digits, with an optional + sign at the beginning, and an optional space somewhere in the middle.