17

I have a table with a phone column, where data may have spaces, dots,dashes or + signs between the numbers. I need to do a search with LIKE wildcards that ignore all those characters, for example:

  • a record may have phone as "+123-456 78.90"
  • a query looking for "6789" or any complete or incomplete sequence of proper digits in order should bring up that record.

Unfortunately I cant cleanup the original table to remove the non-digit characters and do a plain SELECT LIKE %...%.

MYSQL has functions to substitute/remove characters from strings, but can't find a way to use them inside a query with a widlcarded LIKE.

Any help will be much appreciated.

2
  • Which is the server side language ? PHP ?
    – user319198
    Mar 24, 2012 at 8:27
  • 1
    It says mysql and Henry's talking about queries ;)
    – Martijn
    Jan 2, 2014 at 15:19

2 Answers 2

39

I see two ways doing this:

  1. If you allow only a few extra characters than you can prepare a string which is stripped from these extra characters and you use the LIKE operator you normally would

    select * from phoneTable where replace(replace(phone, '+', ''), '-', '') LIKE '%123%'
    

    Of course you need as many replace calls as the number of allowed extra characters

  2. You use regular expressions, let's say you are searching for pattern 123

    select * from phoneTable where phone REGEXP '.*1[^0-9]*2[^0-9]*3'
    
3
  • Once adding the '%..%' to the first option, both of them do the job properly. Much thanks for your help.
    – Henry
    Mar 24, 2012 at 16:05
  • You are right, I forgot out the wildcards, and I didn't try to run the queries. Answer corrected.
    – Hari
    Mar 24, 2012 at 19:21
  • 1
    i'd guess first option is faster
    – Pavel K.
    Oct 30, 2012 at 6:49
5

I had the same problem with partnumbers and unwanted characters. My solution was

SELECT * FROM parts WHERE replace(partnumber, '-', '') LIKE '$searchterm%';
1
  • 5
    how is this answer different from the accepted one?
    – Sp0T
    Jun 17, 2015 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.