Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get every line with string in PHP

Tags:

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?

like image 889
Choops Avatar asked Jul 20 '26 09:07

Choops


2 Answers

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);
like image 123
FuzzyTree Avatar answered Jul 21 '26 22:07

FuzzyTree


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;
}
like image 24
Mark Baker Avatar answered Jul 21 '26 22:07

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!