De.
De.

Reputation: 99

PHP function to get all matched lines from a file

I am trying to search multiple matched lines from a html file and return those lines.

If there is single match then it works. But if there are multiple matches it returns nothing.

Here is the code:

$line = getLineFromFile("abc.html", 'http://www.abc.com/');

echo $line;

function getLineFromFile($file, $string) {
    $lines = file($file);
    foreach($lines as $lineNumber => $line) {
        if(strpos($line, $string) !== false){
            return $lines[$lineNumber];
        }
    }
    return false;
}

Why isn't it returning all the matched lines?

Upvotes: 0

Views: 84

Answers (1)

John Conde
John Conde

Reputation: 219804

Once you return from a function that function call stops executing. You'll need to store your results in an array and then return it.

function getLineFromFile($file, $string) {
    $lines = file($file);
    $matches = array();
    foreach($lines as $lineNumber => $line) {
        if(strpos($line, $string) !== false){
            $matches[] = $lines[$lineNumber];
        }
    }
    return $matches;
}

Just make sure you check for an empty array and not false when checking the results of this function.

Upvotes: 3

Related Questions