如何将数组转换为可在正则表达式中使用的转义字符串?
How to convert an array to an escaped string, which I can use in a regex?
我正在从数据库中查询子网。最终,我会将一堆子网放入一个字符串数组中,结果如下:
array = ['10.1.0.1/24', '10.2.0.2/24', '192.168.0.8/16']
加入上述数组并确保所有 .
和 /
都正确转义的最佳方法是什么,以便我可以查看我拥有的字符串是否与数组中的任何一个子网匹配?
理想情况下我会这样:
if (preg_match(array_as_string, $buffer, $matches)) { }
首先,您可以使用 array_map()
and escape them with preg_quote()
. After this you can use implode()
遍历所有数组值,使它们成为一个字符串,例如
$array = array_map(function($ip){
return preg_quote($ip, "/");
}, $array);
if (preg_match("/\b(" . implode("|", $array) . ")\b/", $buffer, $matches)) { }
所以你最终会得到这样的正则表达式:
/\b(10\.1\.0\.1\/24|10\.2\.0\.2\/24|192\.168\.0\.8\/16)\b/
我正在从数据库中查询子网。最终,我会将一堆子网放入一个字符串数组中,结果如下:
array = ['10.1.0.1/24', '10.2.0.2/24', '192.168.0.8/16']
加入上述数组并确保所有 .
和 /
都正确转义的最佳方法是什么,以便我可以查看我拥有的字符串是否与数组中的任何一个子网匹配?
理想情况下我会这样:
if (preg_match(array_as_string, $buffer, $matches)) { }
首先,您可以使用 array_map()
and escape them with preg_quote()
. After this you can use implode()
遍历所有数组值,使它们成为一个字符串,例如
$array = array_map(function($ip){
return preg_quote($ip, "/");
}, $array);
if (preg_match("/\b(" . implode("|", $array) . ")\b/", $buffer, $matches)) { }
所以你最终会得到这样的正则表达式:
/\b(10\.1\.0\.1\/24|10\.2\.0\.2\/24|192\.168\.0\.8\/16)\b/