user1788210
user1788210

Reputation: 67

PHP Compare a string against the first word of each line of a text file?

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!

Upvotes: 1

Views: 721

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336258

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.

Upvotes: 0

Related Questions