简体   繁体   中英

PHP regex match all lines

I have a file that has multiple lines using tabs, newlines, and whitespaces. In PHP, I'm trying to loop through a file searching for a specific array of keywords.

Here's the array: array('test', 'test2', 'test3')

File contents:

@test
    @test3


       @test2


The code:

$file = file_get_contents('file.txt');
foreach ($array as $k) {
    preg_match('/(@'.$k.')$/m', $file, $m);
}
print_r($m);

The problem is it successfully matches the last element of $array (test3) regardless of any whitespaces before it. Any help would be appreciated, thanks.

The problem in your code is that print_r($m) is outside of the loop. Obviously, you will only print the last match.

The problem is it successfully matches the last element of $array (test3) regardless of any whitespaces before it.

Based on your observations, bolded above , I would say you want a match only if there's no whitespace before it from the beginning of the line, so let's add a character to say that, the ^ :

preg_match('/^(@'.$k.')$/m', $file, $m);

and here is a Rubular to prove it .

$file = file_get_contents('file.txt');
$array = array('test', 'test2', 'test3');
$words = implode('|', $array);

if(preg_match_all('/@('.$words.')\s/i', $file, $m))
{
    print_r($m);
}

this should match everything you need. but it has a small issue which can be fixed if you add a line break or a space after the last keyword in your file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM