Stuart Pinfold
Stuart Pinfold

Reputation: 318

Decipher preg_match

I'm trying to fix some code written by another developer:

 $rexSafety = '@[0-9-\+\s\(\)]+$@';
 if (!preg_match($rexSafety, $_POST['phone'])) $spam = true;

When I type in an 11-digit number (UK standard phone length) without spaces or any other characters, the number (from $_POST['phone']) is marked as spam.

Unfortunately I don't know anything about regular expressions so I was hoping someone would be able to 'decipher' this and tell me what it is expecting?

01234567890 should be a match. It's currently not.

Upvotes: 0

Views: 89

Answers (2)

Machavity
Machavity

Reputation: 31614

Here's the breakdown of your regex. I threw out the @ because he used those as boundary characters. Normally you would use something like / instead (note that's what regex101.com uses)

[0-9-\+\s\(\)]+$

[] indicates a character set we want to match. You put everything you want matched in here. A dash means you have a range so 0-9 will match all decimal numbers

\ is the escape character. It means you want literal characters. So \+ is going to match + in your string

\s is a special class that matches whitespace

\(\) means you want to match any parenthesis ( or )

$ is the end of your string (this is unnecessary since we want anything that matches)

I tweaked it and this should do what you want

if(preg_match('/([^0-9-\+\s\(\)])/', $_POST['phone'])) $spam = true;

By adding ^ we tell regex we don't want anything from this class to match. I also wrapped it in parenthesis to make it a capturing group. That means it will grab the matching elements and return them

Upvotes: 1

pavel
pavel

Reputation: 27082

If you want to check 11 digits, it's \d{11}

 $rexSafety = '~^\d{11}$~';
 if (!preg_match($rexSafety, $_POST['phone'])) $spam = true;

If the format with spaces, dashes, etc. is valid (don't know british phone numbers), first remove these characters to get plain number.

$phone = str_replace(array(' ', '-'), '', $_POST['phone']); // remove spaces & dashes
$rexSafety = '~^\d{11}$~';
if (!preg_match($rexSafety, $phone)) $spam = true;

Upvotes: 1

Related Questions