I am currently looking to find a solution which I can use to find out if selected IP addresses are within a string to replace them with the word private. My problem is that I do not just want to replace always the same IP, but ranges.
For example, I want to find out if a string contains an IP that starts with 123. and if so, change the IP address to the word private
Examples:
123.55.33.10
123.100.10.110
123.1.5.1
The issue is that I don’t know the exact IP addresses and just know how they start, so I can’t censor them by checking the string length etc.
The next issue is that I want to replace various ip’s, for example ones that start with 123. then some that start with 66. and so on. So for my issue, it would be great if you could help me come up with a solution that basically works like:
$ips = array("123.","66.","112.");
and the solution would basically check that if a string contains one of the array values, then replace the IP with the word private – but not just the 123. but any possible combination as a whole, meaning not just $string = str_replace("123.","",$string);
but replacing the whole IP address with private
Reason for this request:
I am building a small script for a school and I need to replace IP’s with the word private, as the search function returns results with IP addresses and I do not want to display them in the results.
The string could look like:
Hans posted with IP 123.1.1.1 on 10.12.2012
So my mission is showing:
Hans posted with IP private on 10.12.2012
So to sum it up, no matter if the string is:
Hans posted with IP 123.112.12.1 on 10.12.2012 or
Hans posted with IP 123.12.15.12 on 10.12.2012 or
Hans posted with IP 123.24.0.100 on 10.12.2012
the solution would replace any IP’s that start with values from my array with the word private
Thank you for your time reading this 🙂
Edit:
I tried the solutions with this string, but it did not work as expected:
<?php
$ip = "The date is 12.10.2012 and this ip 123.1.2.12 should not show but 144.100.1.11 should show while 66.122.11.9 should not show";
$ip = preg_replace('/^(123 | 66 | 112) \. [\d.]+$/x', "private", $ip);
echo $ip;
?>
What should show in the end would be:
The date is 12.10.2012 and this ip private should not show but 144.100.1.11 should show while private should not show
This does not do a sanity check for the validity of IPv4 addresses; it would also match
999.123.999.999. But that check could easily be introduced if necessary.