Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 912
jdnoon Avatar asked Oct 20 '22 11:10

jdnoon


1 Answers

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 )
like image 137
Rizier123 Avatar answered Oct 22 '22 02:10

Rizier123