<p>I have a table which is full of arbitrarily formatted phone numbers, like this</p>
<pre><code>027 123 5644
021 393-5593
(07) 123 456
042123456
</code></pre>
<p>I need to search for a phone number in a similarly arbitrary format ( e.g. <code>07123456</code> should find the entry <code>(07) 123 456</code></p>
<p>The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby)</p>
<pre><code>digits_only = lambda{ |n| n.gsub /[^\d]/, '' }

needle = digits_only[input_phone_number]
haystack.map(&amp;digits_only).include?(needle)
</code></pre>
<p>The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want.</p>
<p>Currently I can think of 2 'solutions'</p>
<ul>
<li>Hack together a franken-query of <code>CONCAT</code> and <code>SUBSTR</code></li>
<li>Insert a <code>%</code> between every character of the needle ( so it's like this: <code>%0%7%1%2%3%4%5%6%</code> )</li>
</ul>
<p>However, neither of these seem like particularly elegant solutions.<br />
Hopefully someone can help or I might be forced to use the %%%%%% solution</p>
<h3>Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over.</h3>
<p>If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback!</p>
<hr />
<blockquote>
<p>could you use a &quot;replace&quot; function to strip out any instances of &quot;(&quot;, &quot;-&quot; and &quot; &quot;,</p>
</blockquote>
<p>I'm not concerned about the result being numeric.
The main characters I need to consider are <code>+</code>, <code>-</code>, <code>(</code>, <code>)</code> and <code>space</code>
So would that solution look like this?</p>
<pre><code>SELECT * FROM people 
WHERE 
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+')
LIKE '123456'
</code></pre>
<p>Wouldn't that be terribly slow?</p>

[{'answer_id': 40880, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 2, 'selected': False, 'text': '<p>An out-of-the-box idea, but could you use a "replace" function to strip out any instances of "(", "-" and " ", and then use an "isnumeric" function to test whether the resulting string is a number?</p>\n\n<p>Then you could do the same to the phone number string you\'re searching for and compare them as integers.</p>\n\n<p>Of course, this won\'t work for numbers like 1800-MATT-ROCKS. :)</p>\n'}, {'answer_id': 40895, 'author': 'crono', 'author_id': 1462, 'author_profile': 'https://Stackoverflow.com/users/1462', 'pm_score': 2, 'selected': False, 'text': '<p>This is a problem with MySQL - the regex function can match, but it can\'t replace. <a href="http://forums.mysql.com/read.php?10,137433,137465" rel="nofollow noreferrer">See this post</a> for a possible solution.</p>\n'}, {'answer_id': 40900, 'author': 'megabytephreak', 'author_id': 4108, 'author_profile': 'https://Stackoverflow.com/users/4108', 'pm_score': 2, 'selected': False, 'text': "<p>Is it possible to run a query to reformat the data to match a desired format and then just run a simple query? That way even if the initial reformatting is slow you it doesn't really matter. </p>\n"}, {'answer_id': 40904, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>MySQL can search based on regular expressions.</p>\n</blockquote>\n\n<p>Sure, but given the arbitrary formatting, if my haystack contained <code>"(027) 123 456"</code> (bear in mind position of spaces can change, it could just as easily be <code>027 12 3456</code> and I wanted to match it with <code>027123456</code>, would my regex therefore need to be this?</p>\n\n<pre><code>"^[\\D]+0[\\D]+2[\\D]+7[\\D]+1[\\D]+2[\\D]+3[\\D]+4[\\D]+5[\\D]+6$"\n</code></pre>\n\n<p>(actually it\'d be worse as the mysql manual doesn\'t seem to indicate it supports <code>\\D</code>)</p>\n\n<p>If that is the case, isn\'t it more or less the same as my %%%%% idea?</p>\n'}, {'answer_id': 40916, 'author': 'crucible', 'author_id': 3717, 'author_profile': 'https://Stackoverflow.com/users/3717', 'pm_score': 0, 'selected': False, 'text': "<p>Just an idea, but couldn't you use Regex to quickly strip out the characters and then compare against that like @Matt Hamilton suggested?</p>\n\n<p>Maybe even set up a view (not sure of mysql on views) that would hold all phone numbers stripped by regex to a plain phone number?</p>\n"}, {'answer_id': 40938, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 0, 'selected': False, 'text': "<p>Woe is me. I ended up doing this:</p>\n\n<pre><code>mre = mobile_number &amp;&amp; ('%' + mobile_number.gsub(/\\D/, '').scan(/./m).join('%'))\n\nfind(:first, :conditions =&gt; ['trim(mobile_phone) like ?', mre])\n</code></pre>\n"}, {'answer_id': 40980, 'author': 'Tanj', 'author_id': 4275, 'author_profile': 'https://Stackoverflow.com/users/4275', 'pm_score': 0, 'selected': False, 'text': '<p>if this is something that is going to happen on a regular basis perhaps modifying the data to be all one format and then setup the search form to strip out any non-alphanumeric (if you allow numbers like 310-BELL) would be a good idea. Having data in an easily searched format is half the battle.</p>\n'}, {'answer_id': 41016, 'author': 'John Dyer', 'author_id': 2862, 'author_profile': 'https://Stackoverflow.com/users/2862', 'pm_score': 5, 'selected': True, 'text': "<p>This looks like a problem from the start.  Any kind of searching you do will require a table scan and we all know that's bad.</p>\n\n<p>How about adding a column with a hash of the current phone numbers after stripping out all formatting characters.  Then you can at least index the hash values and avoid a full blown table scan.</p>\n\n<p>Or is the amount of data small and not expected to grow much?\nThen maybe just sucking all the numbers into the client and running a search there.</p>\n"}, {'answer_id': 95661, 'author': 'Michael Johnson', 'author_id': 17688, 'author_profile': 'https://Stackoverflow.com/users/17688', 'pm_score': 2, 'selected': False, 'text': "<p>My solution would be something along the lines of what John Dyer said. I'd add a second column (e.g. phoneStripped) that gets stripped on insert and update. Index this column and search on it (after stripping your search term, of course).</p>\n\n<p>You could also add a trigger to automatically update the column, although I've not worked with triggers. But like you said, it's really difficult to write the MySQL code to strip the strings, so it's probably easier to just do it in your client code.</p>\n\n<p>(I know this is late, but I just started looking around here :)</p>\n"}, {'answer_id': 911592, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>a possible solution can be found at http: //udf-regexp.php-baustelle.de/trac/</p>\n\n<p>additional package need to be installed, then you can play with REGEXP_REPLACE</p>\n'}, {'answer_id': 2426729, 'author': 'Grbts', 'author_id': 230229, 'author_profile': 'https://Stackoverflow.com/users/230229', 'pm_score': 2, 'selected': False, 'text': '<p>See</p>\n\n<p><a href="http://www.mfs-erp.org/community/blog/find-phone-number-in-database-format-independent" rel="nofollow noreferrer">http://www.mfs-erp.org/community/blog/find-phone-number-in-database-format-independent</a></p>\n\n<p>It is not really an issue that the regular expression would become visually appalling, since only mysql "sees" it. Note that instead of \'+\' (cfr. post with [\\D] from the OP) you should use \'*\' in the regular expression. </p>\n\n<p>Some users are concerned about performance (non-indexed search), but in a table with 100000 customers, this query, when issued from a user interface returns immediately, without noticeable delay. </p>\n'}, {'answer_id': 4585143, 'author': 'Michael Bagryantcev', 'author_id': 529115, 'author_profile': 'https://Stackoverflow.com/users/529115', 'pm_score': 2, 'selected': False, 'text': '<p>i suggest to use php functions, and not mysql patterns, so you will have some code like this:</p>\n\n<pre><code>$tmp_phone = \'\';\nfor ($i=0; $i &lt; strlen($phone); $i++)\n   if (is_numeric($phone[$i]))\n       $tmp_phone .= \'%\'.$phone[$i];\n$tmp_phone .= \'%\';\n$search_condition .= " and phone LIKE \'" . $tmp_phone . "\' ";\n</code></pre>\n'}, {'answer_id': 18870782, 'author': 'Sathish', 'author_id': 1064360, 'author_profile': 'https://Stackoverflow.com/users/1064360', 'pm_score': 0, 'selected': False, 'text': "<p>Create a user defined function to dynamically creates Regex.</p>\n\n<pre><code>DELIMITER //\n\nCREATE FUNCTION udfn_GetPhoneRegex\n(   \n    var_Input VARCHAR(25)\n)\nRETURNS VARCHAR(200)\n\nBEGIN\n    DECLARE iterator INT          DEFAULT 1;\n    DECLARE phoneregex VARCHAR(200)          DEFAULT '';\n\n    DECLARE output   VARCHAR(25) DEFAULT '';\n\n\n   WHILE iterator &lt; (LENGTH(var_Input) + 1) DO\n      IF SUBSTRING(var_Input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN\n         SET output = CONCAT(output, SUBSTRING(var_Input, iterator, 1));\n      END IF;\n      SET iterator = iterator + 1;\n   END WHILE;\n    SET output = RIGHT(output,10);\n    SET iterator = 1;\n    WHILE iterator &lt; (LENGTH(output) + 1) DO\n         SET phoneregex = CONCAT(phoneregex,'[^0-9]*',SUBSTRING(output, iterator, 1));\n         SET iterator = iterator + 1;\n    END WHILE;\n    SET phoneregex = CONCAT(phoneregex,'$');\n   RETURN phoneregex;\nEND//\nDELIMITER ;\n</code></pre>\n\n<hr>\n\n<p>Call that User Defined Function in your stored procedure.</p>\n\n<pre><code>DECLARE var_PhoneNumberRegex        VARCHAR(200);\nSET var_PhoneNumberRegex = udfn_GetPhoneRegex('+ 123 555 7890');\nSELECT * FROM Customer WHERE phonenumber REGEXP var_PhoneNumberRegex;\n</code></pre>\n"}, {'answer_id': 21316683, 'author': 'Nihal', 'author_id': 3229181, 'author_profile': 'https://Stackoverflow.com/users/3229181', 'pm_score': 3, 'selected': False, 'text': '<p>I know this is ancient history, but I found it while looking for a similar solution.</p>\n\n<p>A simple REGEXP may work:</p>\n\n<pre><code>select * from phone_table where phone1 REGEXP "07[^0-9]*123[^0-9]*456"\n</code></pre>\n\n<p>This would match the <code>phonenumber</code> column with or without any separating characters.</p>\n'}, {'answer_id': 41933997, 'author': 'Heisenberg', 'author_id': 2051133, 'author_profile': 'https://Stackoverflow.com/users/2051133', 'pm_score': 0, 'selected': False, 'text': '<p>I would use Google\'s <a href="https://github.com/googlei18n/libphonenumber" rel="nofollow noreferrer">libPhoneNumber</a> to format a number to E164 format. I would add a second column called "e164_number" to store the e164 formatted number and add an index on it. </p>\n'}, {'answer_id': 60871662, 'author': 'Bréndal Teixeira', 'author_id': 5221538, 'author_profile': 'https://Stackoverflow.com/users/5221538', 'pm_score': 2, 'selected': False, 'text': '<p>As John Dyer said, you should consider fixing the data in the DB and store only numbers. However, if you are facing the same situation as mine (I cannot run a update query) the workaround I found was combining 2 queries.</p>\n\n<p>The "inside" query will retrieve all the phone numbers and format them removing the non-numeric characters.</p>\n\n<pre><code>SELECT REGEXP_REPLACE(column_name, \'[^0-9]\', \'\') phone_formatted FROM table_name\n</code></pre>\n\n<p>The result of it will be all phone numbers without any special character. After that the "outside" query just need to get the entry you are looking for.\nThe 2 queries will be:</p>\n\n<pre><code>SELECT phone_formatted FROM (\n    SELECT REGEXP_REPLACE(column_name, \'[^0-9]\', \'\') phone_formatted FROM table_name\n) AS result WHERE phone_formatted = 9999999999\n</code></pre>\n\n<p>Important: the <strong>AS result</strong> is not used but it should be there to avoid erros.</p>\n'}, {'answer_id': 70549733, 'author': 'ideaztech', 'author_id': 3131411, 'author_profile': 'https://Stackoverflow.com/users/3131411', 'pm_score': 1, 'selected': False, 'text': "<p>Here is a working Solution for PHP users.</p>\n<p>This uses a loop in PHP to build the Regular Expression.  Then searches the database in MySQL with the RLIKE operator.</p>\n<pre><code>$phone = '(456) 584-5874'                      // can be any format\n$phone = preg_replace('/[^0-9]/', '', $phone); // strip non-numeric characters\n$len = strlen($phone);                         // get length of phone number\nfor ($i = 0; $i &lt; $len - 1; $i++) {\n    $regex .= $phone[$i] . &quot;[^[:digit:]]*&quot;;\n}\n$regex .= $phone[$len - 1];\n</code></pre>\n<p>This creates a Regular Expression that looks like this: 4[^[:digit:]]*5[^[:digit:]]*6[^[:digit:]]*5[^[:digit:]]*8[^[:digit:]]*4[^[:digit:]]*5[^[:digit:]]*8[^[:digit:]]*7[^[:digit:]]*4</p>\n<p>Now formulate your MySQL something like this:</p>\n<pre><code>$sql = &quot;SELECT Client FROM tb_clients WHERE Phone RLIKE '$regex'&quot;\n</code></pre>\n<p>NOTE:  I tried several of the other posted answers but found performance issues.  For example, on our large database, it took 16 seconds to run the IsNumeric example.  But this solution ran instantly.  And this solution is compatible with older MySQL versions.</p>\n"}, {'answer_id': 71467126, 'author': 'Meloman', 'author_id': 2282880, 'author_profile': 'https://Stackoverflow.com/users/2282880', 'pm_score': 0, 'selected': False, 'text': '<p>In my case, I needed to identify Swiss (CH) mobile phone numbers in the <code>phone</code> column and move them in <code>mobile</code> column.</p>\n<p>As all mobile phone numbers starts with 07x or +417x here is the regex to use :</p>\n<pre><code>/^(\\+[0-9][0-9]\\s*|0|)7.*/mgix\n</code></pre>\n<p>It find all numbers like the following :</p>\n<ul>\n<li>+41 79 123 456 78</li>\n<li>+417612345678</li>\n<li>076 123 456 78</li>\n<li>07812345678</li>\n<li>7712345678</li>\n</ul>\n<p>and ignore all others like theese :</p>\n<ul>\n<li>+41 47 123 456 78</li>\n<li>+413212345678</li>\n<li>021 123 456 78</li>\n<li>02212345678</li>\n<li>3412345678</li>\n</ul>\n<p>In MySQL it gives the following code :</p>\n<pre><code>UPDATE `contact` \nSET `mobile` = `phone`,\n    `phone`  = \'\'\nWHERE `phone` REGEXP \'^(\\\\+[\\D+][0-9]\\\\s*|0|)(7.*)$\'\n</code></pre>\n<blockquote>\n<p>You\'ll need to clean your number from special chars like <code>-/.()</code> before.</p>\n</blockquote>\n<p><a href="https://regex101.com/r/AiWFX8/1" rel="nofollow noreferrer">https://regex101.com/r/AiWFX8/1</a></p>\n'}]
['https://Stackoverflow.com/questions/40873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234/']