PHP - 在文件中找到一个字符串,然后显示它的行号


PHP - Find a string in file then show it's line number

我有一个应用程序需要打开文件,然后在其中找到字符串,并在找到字符串的位置打印一个行号。

例如,文件示例.txt包含几个哈希:

APLF2J51 1a79a4d60de6718e8e5b326e338ae533
EEQJE2YX 66b375b08fc869632935c9e6a9c7f8da O87IGF8R
c458fb5edb84c54f4dc42804622aa0c5 APLF2J51
B7TSW1ZE 1e9eea56686511e9052e6578b56ae018
EEQJE2YX affb23b07576b88d1e9fea50719fb3b7


所以,我想用PHP搜索"1e9eea56686511e9052e6578b56ae018"并打印出它的行号,在本例中为4。

请注意,文件中不会有多个哈希。

我在互联网上找到了一些代码,但似乎没有一个有效。

我试过这个:

<?PHP
$string = "1e9eea56686511e9052e6578b56ae018"; 
$data   = file_get_contents("example.txt"); 
$data   = explode("'n", $data); 
for ($line = 0; $line < count($data); $line++) { 
if (strpos($data[$line], $string) >= 0) { 
die("String $string found at line number: $line"); 
} 
} 
?>

它只是说在第 0 行找到字符串....这是不正确的。

最终应用比这复杂得多...找到行号后,它应该替换其他内容的字符串,并将更改保存到文件中,然后进行进一步处理。

提前致谢:)

一个超基本的解决方案可能是:

$search      = "1e9eea56686511e9052e6578b56ae018";
$lines       = file('example.txt');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
   $line_number = (strpos($line, $search) !== FALSE) ? $key + 1 : $line_number;
}
echo $line_number;

内存节省版本,适用于较大的文件:

$search      = "1e9eea56686511e9052e6578b56ae018";
$line_number = false;
if ($handle = fopen("example.txt", "r")) {
   $count = 0;
   while (($line = fgets($handle, 4096)) !== FALSE and !$line_number) {
      $count++;
      $line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
   }
   fclose($handle);
}
echo $line_number;
function get_line_from_hashes($file, $find){
    $file_content = file_get_contents($file);
    $lines = explode("'n", $file_content);
    foreach($lines as $num => $line){
        $pos = strpos($line, $find);
        if($pos !== false)
            return $num + 1
    }
    return false
}
get_line_from_hashes("arquivo.txt", "asdsadas2e3xe3ceQ@E"); //return some number or false case not found.

如果您需要快速通用的解决方案,也可以用于查找文件中多行文本的行号,请使用以下命令:

$file_content = file_get_contents('example.txt');
$content_before_string = strstr($file_content, $string, true);
if (false !== $content_before_string) {
    $line = count(explode(PHP_EOL, $content_before_string));
    die("String $string found at line number: $line");
}

仅供参考,仅适用于 PHP 5.3.0+。

$pattern = '/1e9eea56686511e9052e6578b56ae018/';
if (preg_match($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
    //PREG_OFFSET_CAPTURE will add offset of the found string to the array of matches
    //now get a substring of the offset length and explode it by 'n
    $lineNumber = count(explode("'n", substr($content, 0, $matches[0][1])));
}

如果文件不是很大,那么只需将文件读入数组file,搜索单词preg_grep,获取该行的索引key并添加1,因为数组从0开始:

$string = "1e9eea56686511e9052e6578b56ae018"; 
echo key(preg_grep("/$string/", file("example.txt"))) + 1;

我发现这很好用并且非常高效;只需按每一行分解文件,然后在数组中搜索搜索词,如下所示:

    function getLineNum($haystack, $needle){
        # Our Count
        $c = 1;
        # Turn our file contents/haystack into an array
        $hsarr = explode("'n", $haystack);
        
        # Iterate through each value in the array as $str
        foreach($hsarr as $str){
            # If the current line contains our needle/hash we are looking for it
            # returns the current count.
            if(strstr($str, $needle)) return $c;
            # If not, Keep adding one for every new line.
            $c++;
        }
        # If nothing is found
        if($c >= count($hsarr)) return 'No hash found!';
    }

编辑:浏览其他答案,我意识到Guilherme Soares也有类似的方法,但使用了strpos,在这种情况下不起作用。所以我在这里根据他的想法做了一些修改:

    function getLineNum($haystack, $needle){
        $hsarr = explode(PHP_EOL, $haystack);
        foreach($hsarr as $num => $str) if(strstr($str, $needle)) return $num + 1;
        return 'No hash found!';
    }

现场演示:https://ideone.com/J4ftV3

相关文章: