swam
swam

Reputation: 303

PHP- Search for string in an array, in a loop

What I would like to do is search a file containing; multiple space delimited words and characters, on multiple lines, using preg_grep, containing a certain string, and store as a variable. I would like to then "for loop" through those matched lines, and search within for yet another string.

For sake of example, assume $c contains all the lines that match variable $a (in an Array?), in the file $o, and returns 9 lines that contain that variable. How

$c = preg_grep("/\b$a\b/", $o);

So I set $max = sizeof($c)

$max = sizeof($c);     // In this example contains 9

Here I try to loop through $c to find variable $b, and would like to print that line that matches

for ($i = 0; $i < $max; $i++) {
    $st = preg_grep("/\b$b\b/", $c);
    echo implode($st, ' ');
}

In the first search if I echo implode($c, ' '), I get all 9 values displayed as one solid string. It seems though using the same technique after my loop, I am not getting the result I want, which is a single line resulting from matching both variables.

Additionally, I know there may be much easier ways to accomplish this, but following this example, Where am I making a mistake(s).

EDIT If it helps, a sample of the text file:

13 04000 Atlanta city GA 394017 +33.762900 -08.4422592
13 56000 North Atlanta CDP PA 27812 0000000147 +33.862550

Where $c = preg_grep("/\b$a\b/", $o); would match both lines And ideally, if $b= PA, the second preg_grep would yeild:

13 56000 North Atlanta CDP PA 27812 0000000147 +33.862550

Upvotes: 2

Views: 82

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Assuming $o is an array of lines:

$result = preg_grep("/\b$b\b/", preg_grep("/\b$a\b/", $o));
echo implode(" ", $result);

This will give an array of elements from $o that match both $a and $b.

Upvotes: 2

Related Questions