在 PHP 中获取带有字符串的每一行


Get every line with string in PHP

我正在尝试从 txt 文件中读取行并返回具有特定字符串的每一行。在这种情况下,我正在寻找"1992"

备选.txt

1223 abcd
1992 dcba
1992 asda

文件.php

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}

当我运行 php 时,当我想接收每行数组时,我会得到"1992 dcba"作为返回。 $line[0] 是 "1992 DCBA",$line[1] 是 "1992 asda"。我该怎么做?

另一种

使用preg_grep的方法

$lines = file('alt.txt');
$results = preg_grep("/1992/", $lines);

preg_grep 将在返回的数组中保留原始键。如果您不希望这样做,请添加以下内容以重新索引返回的数组

$results = array_values($results);

构建一个包含所有有效结果的数组并返回该数组,而不是简单地返回第一个结果

function getLineWithString($fileName, $str) {
    $results = array();
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            $results[] = $line;
        }
    }
    return $results;
}

您当前正在做的是在找到特定字符串后立即返回。您要做的是将行放入数组中并返回数组。因此,您将获得以下内容:

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    $returnLines = array();
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            $returnLines[] = $line;
        }
    }
    return count($returnLines) > 0 ? $returnLines : -1;
} 

我在返回中添加了一行 if 语句,因此如果未添加任何内容,您仍将返回 -1。