从文本文档中获取数据

时间:2018-06-14 13:43:09

标签: php

我正在尝试从文本文件中的一行中获取数据。

我在管道后面搜索一个值和后续数据。

userlist.txt

micky.mcgurk@test.co|Test
michelle.mcgurk@test.co|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应该等于Test,但我得到Test2

3 个答案:

答案 0 :(得分:3)

如果您拆分字符串而不是使用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";
  }

答案 1 :(得分:0)

您的正则表达式中只缺少一些细节 您正在寻找这个正则表达式:

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

您要查找的内容将在$matches[1][0]填写。

我刚刚更改了您的脚本,以便可视化搜索的不同步骤:

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

?>

因此它产生了这个输出:

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

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

)
'
res: 'Test'

答案 2 :(得分:-1)

还在工作......

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

$contents = "micky.mcgurk@test.co|Test\n\r\michelle.mcgurk@test.co|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];
    }
}