user1005424
user1005424

Reputation: 67

PHP preg_match for phone numbers

I'm trying to preg_match phone numbers which can be in any of these formats:

1) 51113333 (8-digit without any space in between)

2) 5111 3333 (8-digit with a space in between)

3) 5111-3333 (8-digit with a hyphen in between)

Thanks!

Upvotes: 1

Views: 4080

Answers (2)

Devin Ceartas
Devin Ceartas

Reputation: 4829

preg_match( "/[^\d]\d{4}[- ]?\d{4}[^\d]/", $number );

I believe. Can't remember if preg_match supports {4} or if you need \d\d\d\d

Upvotes: 1

Brigand
Brigand

Reputation: 86270

This'll do it.

\d{4}[ -]?\d{4}

demo

Note last example. It's much more complicated if this is going to be in other text, like "somestuff12345678otherstuff" because you have to check that the character before and after aren't numbers. Let me know if that's the case.

Upvotes: 2

Related Questions