如何读取文本文件并在冒号前搜索某个字符串,然后显示冒号后的内容?

How to read a text file and search for a certain string before a colon and then show the content after the colon?

我有一个包含如下内容的文件:

test:fOwimWPu0eSaNR8
test2:vogAqsfXpKzCfGr

我希望能够在文件中搜索 test 并将 : 之后的字符串设置为一个变量,以便可以显示、使用等

这是我目前在文件中查找 'test' 的代码。

$file = 'file.txt';
$string = 'test';

$searchFile = file_get_contents($file);
if (preg_match('/\b'.$string.'\b/', $searchFile)) {
    echo 'true';
    // Find String
} else {
    echo 'false';
}

我该怎么做?

这应该适合你:

只需将您的文件放入带有 file() 的数组中,然后简单地 preg_grep() 所有行,这些行在冒号之前有搜索字符串。

<?php

    $file = "file.txt";
    $search = "test";

    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $matches = preg_grep("/^" . preg_quote($search, "/") . ":(.*?)$/", $lines);
    $matches = array_map(function($v){
        return explode(":", $v)[1];
    }, $matches);

    print_r($matches);

?>

输出:

Array ( [0] => fOwimWPu0eSaNR8 )