I am using the following regex in a PHP script to collect IPv4 Addresses and to also perform some validation of the IPv4 addresses.
A txt file of IPs is read into an array with a file()
command, then a foreach loop using preg_match
and this regex matches the IPv4 addresses.
However, it currently includes any leading zeros before each octet.
Is it possible to improve this regex to trim any leading zeros in each octet without completely discarding IPs with leading zeros? I would prefer to do this in a single regex instead of adding an additional function to clear the leading zeros.
/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/
Correct output:
38.10.125.242
38.1.1.24
Incorrect output:
038.010.125.242
038.001.001.024
I have been using Lumadis.be to test, but none of the regexes that I tried from other answers in Stack Overflow seem to work?.