michaelmcgurk
michaelmcgurk

Reputation: 6509

Get text on next line of value found PHP

I have the following text file called people.txt with the contents:

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:

<?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";
}

Upvotes: 1

Views: 44

Answers (3)

Rok D.
Rok D.

Reputation: 244

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

foreach ($keys as $key) { echo $lines[++$key]; }

Upvotes: 1

Rakesh Sojitra
Rakesh Sojitra

Reputation: 3658

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];
}

Upvotes: 2

Bhumi Shah
Bhumi Shah

Reputation: 9476

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];
    }
}

Upvotes: 1

Related Questions