2

I have a string in php like this.

$str = "192.168.10.1;10.192.10.10;" //Contains repeated ip addresses

I want to validate it using regular expression by preg_match function but i am unable to create the regular expression for it. I have created following :/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\;\z/

but this only validate till first ';' not after that.

Thanks in advance

aadi
  • 23
  • 4
  • Check [this](https://regex101.com/r/rZ1kU5/1) – Tushar Jul 29 '15 at 07:36
  • Good article why regex isn't the best solution for this kind of problem: http://blogs.msdn.com/b/oldnewthing/archive/2006/05/22/603788.aspx – take Jul 29 '15 at 07:48

2 Answers2

1

Not an RegEx solution but works fine using ip2long function:

<?php
$str = "192.168.10.1;10.192.10.10;256.10.10.10";

$ips = explode(";", $str);

foreach ($ips as $ip) {
    if (strlen($ip) > 0  && ip2long($ip) === false) {
        echo $ip." is not valid.";
    }
}
take
  • 2,202
  • 2
  • 19
  • 36
  • what if string would be like this 192.168.10.1;10.192.10.10;256.10.10.10;172.168.10.10;10.192.1.200; – aadi Jul 29 '15 at 07:45
  • Your link send to the german version of php.net – Cyrbil Jul 29 '15 at 07:45
  • @aadi: It will work for any length of ip string to validate. also your last string makes the script returns: `256.10.10.10 is not valid.` [try it out here](http://sandbox.onlinephpfunctions.com/code/0f4239da7f5a5e4b4226294f0343494fec77216d) – Cyrbil Jul 29 '15 at 07:48
  • @cyrbil: changed to english one – take Jul 29 '15 at 07:50
  • @aadi If you had tested my example, you had seen that it works also for this string of concated ip addresses. – take Jul 29 '15 at 07:50
0

I suggest using preg_match_all() instead of preg_match(). preg_match_all() catches all patterns found on the subject string..

and you should also remove the ^ in your pattern since it will just match patterns at the beginning of the subject string.

I have tried this code and worked perfectly:

<?php
  $str = "192.168.10.1;10.192.10.10;";
  $pattern = "/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\;/";
  $match = array();
  preg_match_all($pattern, $str, $match);

  print_r($match);
?>

output:

Array
(
    [0] => Array
    (
        [0] => 192.168.10.1;
        [1] => 10.192.10.10;
    )

)
catzilla
  • 1,901
  • 18
  • 31