Regular expression to match an IP Address


/ Published in: PHP
Save to your folder(s)

This is a code to match an IP Address from a source.


Copy this code and paste it in your HTML
  1. /^(?:(?: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]?)$/
  2.  
  3. To use this expression follow the code below.
  4.  
  5. //Save the expression in a variable.
  6. $correct_ip_format = "/^(?:(?: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]?)$/";
  7.  
  8. //some input from a user through a text field or from a server.
  9. $user_input = $_REQUEST['ip_address'];
  10.  
  11. //match the two input's and save it in a variable.
  12. ip_match = preg_match($correct_ip_format, $user_input);
  13.  
  14. //Condition goes here.
  15. if(ip_match){
  16. echo "Correct IP Address";
  17. }
  18. else{
  19. echo "Incorrect IP Address";
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.