Replicate: Searching phone numbers from mysql database

Flávio H. Ferreira
1 min readJan 8, 2020

--

Problem:

Phone number stored in database doesn’t have a proper format.

Example: +977 9841823283992, (61) — (4) — 3432432, 81 2 3882 3232

Now, if you’re trying to do a search for phone numbers, just using

SELECT * FROM table WHERE phone LIKE '%some_number%'

This won’t be able to find number because the spaces, +, -, () won’t be escaped.

What worked for me:

//Remove all non-numeric characters.
$phoneNumber = preg_replace('/\D/', '', $phoneNumber);
//Execute Replace function into correspondent column
SELECT * FROM table WHERE replace(replace(replace(replace(replace(phone , ' ', ''), '+', ''), '-', ''), '(', ''), ')', '') LIKE '%$phoneNumber%'

How it works:

Basically with the above SQL query, we are simply removing all the non numeric characters (+, -, (, )) that could be used in a phone number field by replacing them with a non space. For example if you’re searching for all the numbers that has 8210, the above query will even search for +918 210 12332, (82)-(104)-(1233), 1800 821 0099 etc.|

This is a post just to save my time, if I need it again.
Source: http://www.mircky.com/how-to-search-phone-numbers-from-mysql-database/

--

--

No responses yet