michaelmcgurk
michaelmcgurk

Reputation: 6509

Grab data from text document

I'm trying to grab data from a row in a text file.

I am searching for a value and the subsequent data after the pipe.

userlist.txt:

[email protected]|Test
[email protected]|Test2

PHP:

<?php
$user = "micky.mcgurk";
$file = "userlist.txt";
$search_for = $user;
$contents = file_get_contents($file);
$pattern = sprintf('/\b%s@([^|\s]+)\|/m', preg_quote($search_for));

if (preg_match_all($pattern, $contents, $matches)) {
    echo implode("\n", $matches[1]);
    $resultat = substr(strrchr($contents, '|'), 1);
    echo $resultat;
} else {
   echo "No user found";
}

$resultat should equal Test however I get Test2.

Upvotes: 0

Views: 43

Answers (3)

Bodo Hugo Barwich
Bodo Hugo Barwich

Reputation: 243

There is only a little detail missing in your Regular Expression.
You are looking for this Regular Expression:

$pattern = sprintf('/%s@[^|]+\|(.*)$/m', preg_quote($search_for));

The Content your are looking for will be filled in at $matches[1][0].

I just changed your Script a bit to visualize the different steps of the Search:

<?php
$user = "micky.mcgurk";
$file = "userlist.txt";
$search_for = $user;
$contents = file_get_contents($file);
$pattern = sprintf('/%s@[^|]+\|(.*)$/m', preg_quote($search_for));

echo "ptn: '$pattern'\n";

if (preg_match_all($pattern, $contents, $matches)) {
    echo "mtch: '" .  print_r( $matches, true) . "'\n";
    $resultat = $matches[1][0];
    echo "res: '$resultat'\n";
} else {
   echo "No user found";
}

?>

So it produces this Output:

$ php userlist.php
ptn: '/micky\.mcgurk@[^|]+\|(.*)$/m'
mtch: 'Array
(
    [0] => Array
        (
            [0] => [email protected]|Test
        )

    [1] => Array
        (
            [0] => Test
        )

)
'
res: 'Test'

Upvotes: 0

SiL3NC3
SiL3NC3

Reputation: 770

Also working ...

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

$contents = "[email protected]|Test\n\r\[email protected]|Test2";
$user = "micky.mcgurk";

$contentLines = explode(PHP_EOL, $contents);
$userExists = False;
$result;

foreach ($contentLines as &$line) {
    if (startsWith($line, $user))
    {
        $userExists = True;
        echo explode("|",$line)[1];
    }
}

Upvotes: -1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

It would be easier if you are splitting the string instead of using a RegExp.

<?php
  $user = "micky.mcgurk";
  $file = "userlist.txt";
  $search_for = $user;    // Why so many? Redundant right? Why not remove this?
  $contents = file_get_contents($file);
  $lines = explode(PHP_EOL, $contents);
  $resultat = "";

  $found = false;
  foreach ($lines as $line) {
    $line = explode("|", $line);
    if ($user . "@test.co" == $line[0]) {
      $resultat = $line[1];
      echo $line[1];
    }
  }
  if ($resultat == "") {
    echo "User not found";
  }

Upvotes: 3

Related Questions