简体   繁体   中英

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

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM