How to match using regular expression in PHP – MySQL? [closed]

  mysql, php, regex

I am keeping some IP Address patterns in a table ‘patterns’ having columns ‘id’ INT(11) and ‘ip_address’ VARCHAR(255) type. Like below

  1. 192.0.0.1
  2. 192.0.0."?"
  3. 172.0."?"."?"
  4. 172."?"."?"."?"
  5. ?.?.?.?

I am trying to develop a query which can fetch the best matching IP address pattern type when a IP address is given to it.

For example,

  1. SELECT id FROM patterns where ip_address = ‘192.0.0.1’

    For a exact match like in above query, It should return ‘1’;

  2. SELECT id FROM patterns where ip_address = ‘192.0.0.[0 or 2-999]’

    For a match like in above query, It should return ‘2’;

  3. SELECT id FROM patterns where ip_address = ‘172.0.[0-999].[0 or 2-999]’

    For a match like in above query, It should return ‘3’;

  4. SELECT id FROM patterns where ip_address = ‘172.[0-999].[0-999].[0 or 2-999]’

    For a match like in above query, It should return ‘4’;

  5. The 5th one must be returned in every else case.

Does anyone have any idea how to achieve this using PHP and MySQL?

Thanks.

Source: Ask PHP

LEAVE A COMMENT