Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - How do I mask/hide an IP address (string) using PHP and Regular Expression

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.

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: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Demo

Example output:

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.**.***

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...