1

I have a normal text files with each line having data in the following format.

Mason, James, 13th Avenue, Alexandria, 5812347

Now what I wanted to do was to search for "Mason" in the file and when found, I'd have an array containing all the lines found. The question below does this perfectly with one main problem:

PHP to search within txt file and echo the whole line

PROBLEM: This searches the whole line if every line for a match, I just want to compare my string against the first word in the line or in other words, till the first comma is found.

I cannot seem to be able to "add" the needed modifications to the regular expression to the code provided in the question referenced above. Help would be very appreciated.

Thanks!

Community
  • 1
  • 1
user1788210
  • 67
  • 1
  • 5

1 Answers1

0
preg_match_all(
    '/^    # Match the start of the line
    [^,]*  # Match any number of characters except commas
    Mason  # Match "Mason"
    .*     # Match the rest of the line/mx', 
    $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

gets you all lines where Mason is found before the first comma.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561