[英]Get text on next line of value found PHP
I have the following text file called people.txt
with the contents: 我有以下名为
people.txt
文本文件,其内容如下:
mikey.mcgurk
Boss Man
michelle.mcgurk
Boss Man 2
I'd like to adjust my PHP script to grab the data on the line that follows each username, so if I was searching for mikey.mcgurk
, my script would output Boss Man
. 我想调整我的PHP脚本以获取每个用户名
mikey.mcgurk
的行中的数据,因此,如果我搜索mikey.mcgurk
,我的脚本将输出Boss Man
。
PHP: 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";
}
you can do like this 你可以这样
$contents = file_get_contents($file);
$contents = explode(PHP_EOL, $contents);
if(array_search($searchfor, $contents) !== false){
echo $contents[array_search($searchfor, $contents)+1];
}
You can compare like this: 您可以像这样比较:
$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];
}
}
Instead of using regular expression you can do this by getting all lines in an array 您可以通过获取数组中的所有行来代替使用正则表达式
$lines = explode(PHP_EOL, $contents);
then get keys of results 然后得到结果的关键
$keys = array_keys($lines, $pattern);
and increment keys by 1 to get the next line 并将键增加1以得到下一行
foreach ($keys as $key) { echo $lines[++$key]; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.