0

I want to be able to read through a plain text file and match a number of lines without the need to iterate over the text file multiple times. I am passing in an array with a list of strings I would like to match, which ideally, I would like to put into an array.

I can achieve the desired result using the code below, but it necessitates the reading of the text file multiple times.

function readFile($line){
  $contents = file("test.txt");

  if(preg_match("/$line*/i", $val)){
    return($val);
  }
}

Ideally, I would like to do the following:

// pass an array to the funciton which will parse the file once and match on the elements defined.
$v = readFile(array("test_1", "test_2", "test_2", "test_3"));

// return an array with the matched elements from the search.
print_r($v);

Any help would be much appreciated.

Thanks all!

1
  • you already know the solution: iterate the file once and check each line for the search term. So what's the problem? Commented Oct 2, 2012 at 7:49

2 Answers 2

1
$val = array();
foreach ($contents as $file) {
   foreach ($line as $l) {
      if (stristr($file, $l)) {
         $val[] = $file;
         break; // Don't need to check the other $line values
      }
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Solution worked - thanks for all the help - much appreciataed!
0
$val = array();
foreach ($contents as $file) {
   foreach ($line as $l) {
      if (stristr($file, $l) {
         $val[] = $file;
      }
   }
}

Even if you want to stick with preg_match, the "*" is unnecessary.

5 Comments

You probably want to add a break; statement, so that if $file matches multiple strings it's only added to $val once.
@Barmar I would think he would want every occurrence added, but I'm not sure.
Would probably be better to have it as Explosion Pills has it, so that he can work with the array rather than reloading the file over and over
I meant break out of the inner loop, not the outer loop. Otherwise you can add the same line multiple times.
@Barmar you are adding a line from file every time l matches. As far as we know, l could just be "a", so it would match many lines and a break would be counterintuitive. However, you could use array_unique on the file if you only want unique occurrences.

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.