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


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 )
相关文章: