0

I want to extract the text from within the first set of quotes for each line and put into an array. For example, take this text:

2014-03-20 16:53:39.741 -0700   Information 638 NICOLE  Client "[WebDirect]" opening a connection from "24.114.54.155 (24.114.54.155)" using "iPad Safari 7.0 [fmwebdirect]".
2014-03-20 16:53:39.741 -0700   Information 94  NICOLE  Client "[WebDirect] (24.114.54.155) [24.114.54.155]" opening database "ProShopPartner_v1" as "[Guest]".
2014-03-20 16:58:45.163 -0700   Information 98  NICOLE  Client "[WebDirect] (24.114.54.155) [24.114.54.155]" closing database "ProShopPartner_v1" as "[Guest]".
2014-03-20 16:58:45.163 -0700   Information 22  NICOLE  Client "[WebDirect] (24.114.54.155) [24.114.54.155]" closing a connection.

The array should contain:

[WebDirect]
[WebDirect] (24.114.54.155) [24.114.54.155]
[WebDirect] (24.114.54.155) [24.114.54.155]
[WebDirect] (24.114.54.155) [24.114.54.155]

Right now I have:

$filename = 'C:/Program Files/FileMaker/FileMaker Server/Logs/Access2.txt';

$lines = file($filename, FILE_IGNORE_NEW_LINES);

foreach ($lines as $line) {

    $matches = array();
    preg_match('/^[^"]*"([^"]*)"$/', $lines, $matches);
    $contentInsideFirstQuotes= $matches[1];
}

But it won't give me only the content within the first set of quotes.

Aaron Turecki
  • 345
  • 3
  • 7
  • 24

2 Answers2

1

If you are going line by line, just keep it simple with "([^"]*)" and use preg_match() which will do a non-global search (returning only the first match):

foreach($lines as $line) {
    if(preg_match('/"([^"]*)"/', $line, $matches)) {
        $result[] = $matches[1];
    }
}

If you wanted to do the entire file at once, you could use a global match (preg_match_all()) and prepend .* after the above expression. This will match everything up until a newline character:

"([^"]*)".*

Demo


Finally, to remove the capture group from the initial expression you can use lookarounds:

foreach($lines as $line) {
    if(preg_match('/(?<=")[^"]*(?=")/', $line, $matches)) {
        $result[] = reset($matches); // $matches[0]
    }
}

Notes: I use [^"]* (greedy) instead of .*? (lazy) because it is more specific and will prevent unnecessary backtracking. Also, if you want to require something between the quotations (i.e., test "" "foo bar" returning foo bar not ) then change the * to +.

Sam
  • 20,096
  • 2
  • 45
  • 71
0

Try this

  $filename = 'C:/Program Files/FileMaker/FileMaker Server/Logs/Access2.txt';

    $lines = file($filename, FILE_IGNORE_NEW_LINES);
    $result = array();
    foreach ($lines as $line) {
        preg_match('/^[^"]*"([^"]*)"$/', $line, $matches);
        $result[] = $matches[1];
    }

print_r($result);
turson
  • 421
  • 2
  • 9