【问题标题】:How to read a text file and search for a certain string before a colon and then show the content after the colon?如何读取文本文件并在冒号前搜索某个字符串,然后在冒号后显示内容?
【发布时间】:2015-08-06 15:59:12
【问题描述】:

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

test:fOwimWPu0eSaNR8
test2:vogAqsfXpKzCfGr

我希望能够在文件中搜索 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';
}

我该怎么做呢?

【问题讨论】:

    标签: php regex file preg-match file-get-contents


    【解决方案1】:

    这应该适合你:

    只需将您的文件放入带有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 )
    

    【讨论】:

    • 您的回复有效,但它只适用于文件中的第一行,它不适用于后面的任何行,有什么原因吗?
    • @jdnoon 它仍然有效,但索引是文件中的行号。因此,如果您想重新索引数组,只需简单地将 array_values() 调用包裹在 array_map() 调用
    猜你喜欢
    • 2017-09-27
    • 2016-07-31
    • 2013-07-05
    • 2013-12-19
    • 2019-09-27
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多