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

  • Pingback: PHP Regex IPv6 with preg_match()

  • zlatko

    Can you link your phpinfo somewhere? I can’t get a match for an IP on my sample code and I can get a match here.

  • Cristi

    Can you explain the steps of the regex pattern, ’cause it might work in php, but it won’t work in any other language, and is a hell to adapted it since I don’t know what are you doing.

    • http://mebsd.com/ Jake Smith

      Check out this page it has many IPv6 regex examples for different languages, hopefully you can find something that works for you here http://home.deds.nl/~aeron/regex/

  • BBcan177

    Unfortunately these IPs don’t seem to be validated with this regex: 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32