如何使用 PHP 和正则表达式屏蔽/隐藏 IP 地址(字符串) [英] How do I mask/hide an IP address (string) using PHP and Regular Expression
问题描述
我想使用正则表达式隐藏 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屋!