简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM