如何使用 PHP 和正则表达式屏蔽/隐藏 IP 地址(字符串) [英] How do I mask/hide an IP address (string) using PHP and Regular Expression

查看:36
本文介绍了如何使用 PHP 和正则表达式屏蔽/隐藏 IP 地址(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式隐藏 IP 地址的最后两个部分,问题是星号 (*) 必须与这些部分的长度匹配.

I would like to hide the last two sections from an IP address using regular expression the problem is that the asterix (*) must match the length of those sections.

例如:10.101.12.100 应该重新格式化为 10.101.**.***

Eg: 10.101.12.100 should be re-formated into 10.101.**.***

这是我正在使用的代码:

This is the code I'm working with :

echo preg_replace('!(\d+).(\d+).\d+.\d+!s', '${1}.${2}.***.***', "10.101.12.100");
// Return: 10.101.***.***

可以使用正则表达式吗?

Is that possible using regex ?

PS: 我知道我可以使用 explode('.', ...)str_repeat('*', strlen(...)) 但我发现 preg_replace 是一个更简洁的解决方案.我正在寻找oneliner"解决方案.

PS: I know I could break it using explode('.', ...) along with str_repeat('*', strlen(...)) but I find preg_replace a cleaner solution. I'm looking for a "oneliner" solution.

推荐答案

使用否定前瞻(基本上,让正则表达式取消前两个八位字节的资格,然后从其后进行正常的数字替换.)例如

Use a negative look-ahead (Basically, have regex disqualify the first two octets, then do a normal digit replace from thereafter.) e.g.

(?!\d{1,3}\.\d{1,3}\.)\d

演示

示例输出:

237.134.85.92 -> 237.134.**.**
173.14.176.182 -> 173.14.***.***
167.209.41.203 -> 167.209.**.***
137.133.204.130 -> 137.133.***.***
93.108.72.157 -> 93.108.**.***

这篇关于如何使用 PHP 和正则表达式屏蔽/隐藏 IP 地址(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆