Search code examples
phparraysregexstringpreg-match

How to convert an array to an escaped string, which I can use in a regex?


I'm querying for subnets from a database. Ultimately I'll get a bunch of subnets into an array of strings with results like:

array = ['10.1.0.1/24', '10.2.0.2/24', '192.168.0.8/16']

What's the best way to join the array above and ensure all . and / are properly escaped so I can see if a string I have matches any one of the subnets in the array?

Ideally I'd have something like:

if (preg_match(array_as_string, $buffer, $matches)) { }

Solution

  • First you can loop through all array values with array_map() and escape them with preg_quote(). After this you can use implode() to make them to a string, e.g.

    $array = array_map(function($ip){
        return preg_quote($ip, "/");
    }, $array);
    
    if (preg_match("/\b(" . implode("|", $array) . ")\b/", $buffer, $matches)) { }
    

    So you will end up with a regex like this:

    /\b(10\.1\.0\.1\/24|10\.2\.0\.2\/24|192\.168\.0\.8\/16)\b/