我有以下文本文件people.txt
,内容为:
mikey.mcgurk
Boss Man
michelle.mcgurk
Boss Man 2
我想调整我的PHP脚本以获取每个用户名后面的行上的数据,因此如果我搜索mikey.mcgurk
,我的脚本将输出Boss Man
。
PHP:
<?php //
$file = 'people.txt';
$searchfor = "mikey.mcgurk";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
// write all of this to a text file
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
答案 0 :(得分:2)
你可以这样做
$contents = file_get_contents($file);
$contents = explode(PHP_EOL, $contents);
if(array_search($searchfor, $contents) !== false){
echo $contents[array_search($searchfor, $contents)+1];
}
答案 1 :(得分:1)
您可以这样比较:
$contents = file_get_contents($file);
$lines = explode("\n",$contents);
for($i = 0; $i < count($lines); $i++) {
if( $lines[$i] ==$searchfor ) {
echo "Username ".$lines[$i+1];
}
}
答案 2 :(得分:1)
不是使用正则表达式,而是通过获取数组中的所有行来实现此目的
$lines = explode(PHP_EOL, $contents);
然后获取结果键
$keys = array_keys($lines, $pattern);
并将键增加1以获取下一行
foreach ($keys as $key) {
echo $lines[++$key];
}