如何读取文本文件并在冒号之前搜索某个字符串,然后在冒号之后显示内容? [英] 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
我希望能够在文件中搜索test
,并将:
之后的字符串设置为变量,以便可以显示,使用等.
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';
}
我该怎么做?
推荐答案
这应该对您有用:
只需使用file()
将文件放入数组,然后简单地preg_grep()
所有行(在冒号前都有搜索字符串)即可.
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);
?>
输出:
Array ( [0] => fOwimWPu0eSaNR8 )
这篇关于如何读取文本文件并在冒号之前搜索某个字符串,然后在冒号之后显示内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文