Mikulas Dite
Mikulas Dite

Reputation: 7941

Finding a line number certain text is on

what is the best way to find on which line certain string is on? I know I could iterate though all of the lines, but the catch is that the string being searched might be multiline. Would this be solvable by regex for example? Thanks

Upvotes: 0

Views: 355

Answers (3)

Galen
Galen

Reputation: 30170

I always try and avoid loops when i can

loopless...

function getLine( $haystack, $needle ) {
    return substr_count( substr( $haystack, 0, strpos($haystack, $needle ) ), "\n" ) + 1;
}

working example

Upvotes: 0

ircmaxell
ircmaxell

Reputation: 165201

Well, if you're talking about a file the best way it to iterate:

$lines = 0;
while ($line = fgets($f)) {
    $lines++;
    if (stripos($line, $searchWord) !== false) {
        $foundOnLine = $lines;
        break;
    }
}

But if it's a string, you could do a little bit of a hack (which finds the text before the match, and then returns the number of matches):

$foundOnLine = preg_match_all('#\n#', stristr($string, $searchWord, true), $a);

But notice that it will return line 0 for both not-found-in-string and found-on-first-line. If you want to distinguish them:

$found = function($string, $searchWord) {
    $pretext = stristr($string, $searchWord, true);
    $a = null;
    return $pretext === false ? false : preg_match_all('#\n#', $pretext, $a);
}

That will return false if not found, or 0 if on the first line...

Upvotes: 0

wallyk
wallyk

Reputation: 57774

It's solvable. First search for the pattern where all the lines are searched at once separated, for example with \n's. Then count the number of \n's before it.

Upvotes: 1

Related Questions