Skip to content
Advertisement

If variable contains word, show it and get line number

So I trying to check “if text file on server contains word, show it and display his line number” but i only know how to check “if text file contains word”. Anybody have sugesstions how to do it? I saw many tutorials but there are about local text files.

For now I have only this function

   function readStrLine($str, $n) {
    $lines = explode(PHP_EOL, $str);
    return $lines[$n-1];
}

But I need line number.

For example I have text file saved on my server. examplesite.com/file.txt with this content:

 ABCDEF
 123456
 QWERTY

For now program reads content and checks if there is containing word. But I need the number of this line where this word is.

Advertisement

Answer

Example:

<?php

$desiredWord = 'apple';

$fileString = file_get_contents('asd.txt');

$lines = explode(PHP_EOL, $fileString);

$results = [];
foreach ($lines as $lineNumber => $line) {
    if (strpos($line, $desiredWord) !== false) {
        $results[] = ($lineNumber + 1) .":{$line}";
    }
}

foreach ($results as $result) {
    echo '<pre>' . print_r($result, true) . '</pre>';
}

Input file content:

apple
asdfsdf
vs
werwerwer
llll
hhheeheh
there is an apple on the tree
the tree does not fall far from it's apple

Output:

1:apple

7:there is an apple on the tree

8:the tree does not fall far from it's apple

You can go through on the lines with a foreach. The $lineNumber key contains the line index you are currently reading, and the $line is the string of the current line. The explode function will index your array from 0, so first line index will be 0 when you read it. That’s why the + 1 in this line: $results[] = ($lineNumber + 1) .":{$line}";

With the if (strpos($line, $desiredWord) !== false) you are checking if you find the desired word in the given line. If you want only one result you can return here, but if you would like to collect all of the lines where the word can be found, then you store the found lines like this in the $results

Finally you can check the findings with the second foreach, or any other way – depends on your implementation.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement