GiantDuck
GiantDuck

Reputation: 1064

Return line including found string

Say I have an HTML document: (Excerpt below with line numbers)

30 - <div id="myDiv">
31 -   <span class="mySpan">Some Text</span>

I am using PHP:

$html = file_get_contents('myHtml.html')

I want to find the line number on which a string is found (Let's assume there's only one occurrence of the string in the document), and return the entire contents found on that line. For example,

getLine('myDiv'); //returns <div id="myDiv">
getLine('class="mySpan"'); //returns <span class="mySpan">Some Text</span>

How can I do this? Thank you!

Upvotes: 0

Views: 51

Answers (1)

Claudi
Claudi

Reputation: 5416

Understanding line as the set of characters separated by a newline character ('\n'), you can explode the $html string as follows:

$lines = explode("\n", $html); 

Then iterate each line while keeping a line count:

$lineno = 1;
foreach ($lines as $line) {
    if (strstr($line, $what_to_find) !== FALSE) {
        //Match
        echo "Line $lineno: $line\n";
    }
    $lineno++;
}

Upvotes: 2

Related Questions