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

独自空忆成欢 提交于 2019-12-10 14:05:50

问题


I have a file that contains something like this:

test:fOwimWPu0eSaNR8
test2:vogAqsfXpKzCfGr

I would like to be able to search the file for say test and it set the string after the : to a variable so it can be displayed, used etc.

Here is the code I have so far for finding 'test' in the file.

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

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

How would I go about doing this?


回答1:


This should work for you:

Just get your file into an array with file() and then simply preg_grep() all lines, which have the search string before the colon.

<?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);

?>

output:

Array ( [0] => fOwimWPu0eSaNR8 )


来源:https://stackoverflow.com/questions/30433793/how-to-read-a-text-file-and-search-for-a-certain-string-before-a-colon-and-then

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!