1

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.

jotik
  • 17,044
  • 13
  • 58
  • 123
Ktari zied
  • 157
  • 1
  • 2
  • 13

3 Answers3

2

You can use

preg_match('~^[a-z]{2}39\.[a-z]{4} \(([\d.]+)~m', $myfile_contents, $matches);
print_r($matches[1]);

See the regex demo

I added a \( to match a literal ( and used a capturing group around [\d.]+ (1 or more digits or dots) that matches the IP that can be retrieved using [1] index in $matches. The ~m enables a multiline mode so that ^ could match the beginning of a line, not just the string start.

UPDATE

If you need to create a dynamic regex with a literal string in it, you should think about using preg_quote:

$myfile = file('file.txt');
$search = "pc39.home";           // <= a literal string, no pattern
foreach ($myfile as $lineContent)
{
     $lines=preg_match('/' . preg_quote($search, "/") . ' \(([\d.]+)\)/', $lineContent, $out);
     echo($out[1]);
}

You also need a single quoted literal in ' \(([\d.]+)\)/' since the \ must be literal \ symbols (yes, PHP resolves \ as a literal \ with non-existing escape sequences, but why put it to PHP?).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

the solution is:

$myfile = file('file.txt');
            $search = "pc39\.home";
            foreach ($myfile as $lineContent)
            {
               $lines=preg_match("/" . $search ." \(([\d.]+)\)/", $lineContent, $out);
               echo($out[1]);
            }
Ktari zied
  • 157
  • 1
  • 2
  • 13
0

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);
Andreas
  • 23,610
  • 6
  • 30
  • 62