I want to do a search in a MySQL database for phone numbers.
At present with this query:
SELECT person FROM people WHERE phone_number RLIKE \'1234567
I can think of two ways to do it, neither as elegant as I'd hoped though.
First: Use regex in RLIKE
to allow spaces and brackets everywhere:
SELECT person
FROM people
WHERE phone_number RLIKE '[() ]*1[() ]*2[() ]*3[() ]*4[() ]*5[() ]*6[() ]*7[() ]*8[() ]*9'
It basically says there can be brackets and spaces in between each number. It's a bit awkward to make the string though. If you are calling mySQL from another language (say php) you could use the other language to turn '123456789' into 'x1x2x3x4x5x6x7x8x9' where 'x' is [() ]*
.
Second: use mysql REPLACE
to remove spaces and brackets before doing comparison:
SELECT person
FROM people
WHERE REPLACE(REPLACE(REPLACE(phone_number,' ',''),'(',''),')','') = '123456789';
This successively replaces spaces, open brackets, and closing brackets in phone_number
with ''.
I think I prefer this second method. To remove all spaces you just need REPLACE(phone_number,' ','')
and to remove all ()
you need two REPLACE
.
I suppose the first is more flexible with respect to adding extra characters though. It's a shame MySQL doesn't have a regex-enabled REPLACE
!