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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With