Choops
Choops

Reputation: 75

Get every line with string in PHP

I'm trying to read lines from a txt file and return every line that has a certain string on it. In this case I'm looking for "1992"

alt.txt

1223 abcd
1992 dcba
1992 asda

file.php

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}

When I run the php, I get "1992 dcba" as the return, when I want to receive an array with each line. $line[0] would be "1992 dcba" and $line[1] would be "1992 asda". How could I do this?

Upvotes: 3

Views: 1030

Answers (3)

FuzzyTree
FuzzyTree

Reputation: 32392

Another way using preg_grep

$lines = file('alt.txt');
$results = preg_grep("/1992/", $lines);

preg_grep will preserve the original keys in the returned array. If you don't want that add the following to reindex the returned array

$results = array_values($results);

Upvotes: 4

Edwin
Edwin

Reputation: 1135

What you are currently doing is returning as soon as it finds a particular string. What you want to do is put the line into an array and return the array. So you would get the following:

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    $returnLines = array();

    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            $returnLines[] = $line;
        }
    }
    return count($returnLines) > 0 ? $returnLines : -1;
} 

I've added a single line if statement on the return so you will still return -1 if nothing was added.

Upvotes: 3

Mark Baker
Mark Baker

Reputation: 212412

Build an array of all the valid results and return that, rather than simply returning the first result

function getLineWithString($fileName, $str) {
    $results = array();
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            $results[] = $line;
        }
    }
    return $results;
}

Upvotes: 3

Related Questions