以及preg_replace()
是有点慢有更好的方法来做到这一点像explode()
,如果你想隐藏IP的最后一部分,这样做:
<?php
$ip = "192.168.0.1";
$ip_items = explode('.', $ip);
$filtered_ip = ''; //The var to store the filtered ip
foreach($ip_items as $item) {
if($item == end($ip_items)) { //check if its the last part of the IP
$ip_part = '***';
} else {
$ip_part = $item . '.';
}
$filtered_ip .= $ip_part;
}
echo $filtered_ip;
?>
结果:192.168.0.***
和如果你想过滤的其他部分的IP像第一个使用$ip_items[0]
而不是end($ip_items)
例如:
<?php
$ip = "192.168.0.1";
$ip_items = explode('.', $ip);
$filtered_ip = ''; //The var to store the filtered ip
foreach($ip_items as $item) {
if($item == $ip_items[0]) { //check if its the first part of the IP
$ip_part = '***.'; //we added the '.' to that one because its the first item
} else {
$ip_part = $item . '.';
}
$filtered_ip .= $ip_part;
}
echo $filtered_ip;
?>
结果:***.168.0.1.
编辑:和关于第二个问题,你可以使用str_length
得到的长度和使用str_repeat
重复字符
例如:
<?php
$ip = "192.168.0.1";
$ip_items = explode('.', $ip);
$filtered_ip = ''; //The var to store the filtered ip
foreach($ip_items as $item) {
if($item == end($ip_items)) { //check if its the last part of the IP
$ip_part = str_repeat("*", strlen($item)) ;
} else {
$ip_part = $item . '.';
}
$filtered_ip .= $ip_part;
}
echo $filtered_ip;
?>