Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

php - regex for all UK telephone numbers

I am trying to validate UK telephone numbers, which are in the format of:

01234 567890

01234567890

02012345678

020 1234 5678

I have the following regex, which works for all apart from the 020 1234 5678

^s*(?(020[7,8]{1})?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3})?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})s*$

Does anyone know why this is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are missing a closing square bracket

^s*(?(020[7,8]{1})?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3})?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})s*$
                                      ^
                                     here

This should be working

^s*(?(020[7,8]{1})?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3})?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})s*$

Further you can remove some stuff from your expression.

{1} is not need every character is still matched once

[ ] is also not needed, just replace it with a space

[8,9] is wrong. it will match 8, 9 and , . Use [89] is correct.

Then it would look like that

^s*(?(020[78])? ?[1-9][0-9]{2} ?[0-9]{4})|(0[1-8][0-9]{3})? ?[1-9][0-9]{2} ?[0-9]{3})s*$

If you want to allow this not matched pattern 020 1234 5678 you could do for example

^s*(?(020[78]?)? ?[1-9][0-9]{2,3} ?[0-9]{4})$|^(0[1-8][0-9]{3})? ?[1-9][0-9]{2} ?[0-9]{3})s*$
               ^                 ^^
made the [78] optional        allows no 2 or 3 of `[0-9]`

See it here on Regexr

I have no clue if this is a valid UK phone number!

I fixed here also another bug in the regex a missing $ before and a missing ^ after the pipe |


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...