IPv6: Short IPv6 Regexp – PHP preg_match() example

Back in July 2011 I posted an example IPv6 regular expression using PCRE via PHP’s preg_match() function to check for a valid IPv6 address. Find it here. My example was long, and had some issues. It didn’t match short hand IPv6 addresses properly and it was not very elegant. Recently a visitor commented on this regex and suggested a much better way of doing it.

IPv6 Regexp:


If you’re interested in seeing some more IPv6 regex examples for other languages you should check this link Shortest IPv6 Validation Regular Expression (RegEx).

Here is the updated version, I have not found any bugs yet so please feel free to test it below or try it out in your own code. Let us know how you get on.

You can try out this function here, give it a go!

Example IPv6 addresses

  • 2001:2d12:c4fe:5afe::1
  • 2a00:1450:400c:c01::68
  • ::1

Here is the source, a better way of matching IPv6 using PHP preg_match()

function valid_ipv6_address( $ipv6 )
    $regex = '/^(((?=(?>.*?(::))(?!.+3)))3?|([dA-F]{1,4}(3|:(?!$)|$)|2))(?4){5}((?4){2}|(25[0-5]|(2[0-4]|1d|[1-9])?d)(.(?7)){3})z/i';
        if(!preg_match($regex, $ipv6))
        return (false); // is not a valid IPv6 Address

    return (true);

You may also like...