[英]Get text on next line of value found PHP
我有以下名为people.txt
文本文件,其内容如下:
mikey.mcgurk
Boss Man
michelle.mcgurk
Boss Man 2
我想调整我的PHP脚本以获取每个用户名mikey.mcgurk
的行中的数据,因此,如果我搜索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";
}
你可以这样
$contents = file_get_contents($file);
$contents = explode(PHP_EOL, $contents);
if(array_search($searchfor, $contents) !== false){
echo $contents[array_search($searchfor, $contents)+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];
}
}
您可以通过获取数组中的所有行来代替使用正则表达式
$lines = explode(PHP_EOL, $contents);
然后得到结果的关键
$keys = array_keys($lines, $pattern);
并将键增加1以得到下一行
foreach ($keys as $key) { echo $lines[++$key]; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.