[英]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.