Skip to content

Instantly share code, notes, and snippets.

@phenomax
Created June 5, 2016 08:30
Show Gist options
  • Save phenomax/50eaa09cf46c1da8d98b10d6a1858a54 to your computer and use it in GitHub Desktop.
Save phenomax/50eaa09cf46c1da8d98b10d6a1858a54 to your computer and use it in GitHub Desktop.

Revisions

  1. Max created this gist Jun 5, 2016.
    20 changes: 20 additions & 0 deletions regex.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    /**
    * @param $str the string to check
    * @return bool whether the String $str is a valid ip or not
    */
    function isValidIP($str)
    {
    /**
    * Alternative solution using filter_var
    *
    * return (bool)filter_var($str, FILTER_VALIDATE_IP);
    */

    /**
    * Normally preg_match returns "1" when there is a match between the pattern and the provided $str.
    * By casting it to (bool), we ensure that our result is a boolean.
    * This regex should validate every IPv4 addresses, which is no local adress (e.g. 127.0.0.1 or 192.168.2.1).
    * This pattern was debugged using https://regex101.com/
    */
    return (bool)preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$', $str);
    }