如何将数组转换为转义字符串,我可以在正则表达式中使用?

时间:2021-03-31 19:24:53

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)) { }

1 个解决方案

#1


2  

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_map()遍历所有数组值,并使用preg_quote()对其进行转义。在此之后,您可以使用implode()将它们变为字符串,例如

$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/

#1


2  

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_map()遍历所有数组值,并使用preg_quote()对其进行转义。在此之后,您可以使用implode()将它们变为字符串,例如

$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/