Search code examples
phpregexpreg-grep

Regular expression to match IP addresses


I have file.txt which contains this data:

livebox.home (192.168.1.1)
set-top-box41.home (192.168.1.10)
pc38.home (192.168.1.11)
pc43.home (192.168.1.12)
pc39.home (192.168.1.15)

I want to extract the IP of pc39.home. I have used this regular expression but it not work:

preg_grep("#^[a-z]{2}39.[a-z]{4} \d{3}\.\d{3}\.\d{1}\.\d{2}#",$myfile);

The result should be 192.168.1.15.


Solution

  • with this you can just change the $search if you want to caputure any of the other IPs.

    $search = "pc39\.home";
    preg_match("/" . $search ." \(([\d.]+)\)/", $myfile, $out);