Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 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 Reply

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 |


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...