SomeRandomDude
SomeRandomDude

Reputation: 193

Need to get line number in text file matching string

I need to get the line number of a text file using PHP. The line I need is "WANT THIS LINE".

I tried using file() to put the file lines in an array and search using array_search() but it won't return the line number. In this example I would need to return 3 as the line number.

$file = file("file.txt");
$key = array_search("WANT", $file);
echo $key;

Text File:

First Line of Code
Some Other Line
WANT THIS LINE
Last Line

Upvotes: 3

Views: 8997

Answers (2)

Gordon
Gordon

Reputation: 316969

This should be more memory efficient than loading the file into an array

foreach (new SplFileObject('filename.txt') as $lineNumber => $lineContent) {
    if(trim($lineContent) === 'WANT THIS LINE') {
        echo $lineNumber; // zero-based
        break;
    }
}

If you just want to search for parts of a word, replace

if(trim($lineContent) === 'WANT THIS LINE') {

with

if (FALSE !== strpos($lineContent, 'WANT')) {

Upvotes: 3

Mark Baker
Mark Baker

Reputation: 212412

array_search() is looking for an exact match. You'll need to loop through the array entries looking for a partial match

$key = 'WANT';
$found = false;
foreach ($file as $lineNumber => $line) {
    if (strpos($line,$key) !== false) {
       $found = true;
       $lineNumber++;
       break;
    }
}
if ($found) {
   echo "Found at line $lineNumber";
}

Upvotes: 5

Related Questions