以下用<ip>
替换任何IP地址。
$match = '/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/';
$replace = '<ip>';
$CurrentText = preg_replace($match, $replace, $CurrentText);
如何只替换不以192或10开头的IP地址。
即。 10.0.0.1不应该匹配,但11.0.0.1应该匹配。
答案 0 :(得分:4)
试试这个:
$match = '/(?<!\d)(?!10\.|192\.)\d{1,3}(?>\.\d{1,3}){3}/';
答案 1 :(得分:1)
私有IP地址不能像这样工作,特别是Class-C私有网192.168.0.0/16。完全有效的公共IP地址可以从192开始。
使用类似的东西:
function ip_is_private ($ip) {
$pri_addrs = array (
'10.0.0.0|10.255.255.255', // single class A network
'172.16.0.0|172.31.255.255', // 16 contiguous class B network
'192.168.0.0|192.168.255.255', // 256 contiguous class C network
'169.254.0.0|169.254.255.255', // Link-local address also refered to as Automatic Private IP Addressing
'127.0.0.0|127.255.255.255' // localhost
);
$long_ip = ip2long ($ip);
if ($long_ip != -1) {
foreach ($pri_addrs AS $pri_addr) {
list ($start, $end) = explode('|', $pri_addr);
// IF IS PRIVATE
if ($long_ip >= ip2long ($start) && $long_ip <= ip2long ($end)) {
return true;
}
}
}
return false;
}
答案 2 :(得分:1)
// test string
$string = '192.168.1.1,10.0.0.1,1.2.3.4,BAD:256.257.258.259';
// first must be between 1-255
$npf = '([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])';
// next must be between 0-255
$npn = '([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])';
// ip has to be bordered by \b regex to be valid
$pattern = "~\\b{$npf}\\.{$npn}\\.{$npn}\\.{$npn}\\b~s";
// replace with a callback
$string = preg_replace_callback($pattern, function($match){
// play with them as you wish
$ip = $match[0];
$match1 = intval($match[1]);
if(in_array($match1, array(10, 192))){
return $ip;
}
return '<ip>';
}, $string);
// clean up
unset($npf, $npn);
// output string
var_dump($string);
代码被评论,应该有意义。
<强>奖金强>:
这些是私有IP范围。
$private_ranges = array(
// 10.0.0.1 to 10.255.255.254
ip2long('10.0.0.0') => ip2long('10.255.255.255'),
// 172.16.0.1 to 172.31.255.254
ip2long('172.16.0.0') => ip2long('172.31.255.255'),
// 192.168.0.1 to 192.168.255.254
ip2long('192.168.0.0') => ip2long('192.168.255.255'),
// 127.0.0.0 to 127.255.255.255
ip2long('127.0.0.0') => ip2long('127.255.255.255'),
);
在ip2long()
对$match[0]
的数组中使用它们,以便更好地进行点击测试。
答案 3 :(得分:0)
使用一些花哨的preg_replace_callback()
使其更容易理解:
$ip = "192.168.1.1";
$match = '/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/';
$replace = '<ip>';
$ip = preg_replace_callback($match, function($matches) use ($replace) { //Run this function every time there's a match. Bring $replace from the outside.
$first = array_shift(explode(".", $matches[0])); //Get first segment of the IP
if (!in_array($first, ["192", "10"])) { //If the segment isn't 192 or 10
return $replace; //Return the replacement (<ip>)
}
return $matches[0]; //Else, return the IP unchanged.
}, $ip);
echo $ip;