You need to get the line number in the line matching the text file

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

I tried using file () to put the lines of the file into an array and do a search using array_search (), but it will not return the line number. In this example, I will 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
+3
source share
2 answers

array_search () is looking for an exact match. You will need to skip array entries that are 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";
}
+5
source

It should be more memory than loading a 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 find parts of a word, replace

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

with

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

Source: https://habr.com/ru/post/1790554/


All Articles