1

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.

1
  • What is your question? If you match strings, you should resort to strpos Commented May 25, 2013 at 8:12

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.