PHP - 读取.txt中的数据并输出$Data


PHP - Read data in .txt and output $Data?

你好,所以我有一个文本文件,如下所示

数据.txt

data e.g. username

我需要把它放进$tag

文件.php

if ($username == "$data") { echo "User Found" } else{ echo "User not found";}

对此有任何帮助真的会很好:)?

一种

可以在这里使用的方法,也是我从我的一个脚本库中获取的,是利用preg_match()并使用'b单词边界选项和i不敏感大小写开关,这将适用于单行或多行数据。将匹配"约翰"或"约翰",例如。

<?php 
$_POST['name'] = "john";
$var = trim($_POST['name']); // should there be a space entered
// $var = $_POST['name'];
$pattern = "/'b$var'b/i";
$fh = fopen('data.txt', 'r') or die("Can't open file");
while (!feof($fh)) {
    $line = fgets($fh, 4096);
    if (preg_match($pattern, $line)) { 
echo "MATCH FOUND";
    }
else{
echo "NOT FOUND";
}
}
fclose($fh);

但是,如果条目由空格分隔,这将不起作用。 即:"约翰·多伊"。

如果是这种情况,您将需要使用以下内容,stripos()不区分大小写。

<?php 
$_POST['name'] = "john doe";
$search = trim($_POST['name']);
// $search = $_POST['name'];

// Read from file
$lines = file('data.txt');
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(stripos($line, $search) !== false){
    echo "Found: " . $line; }
}

引用:

  • http://php.net/manual/en/function.preg-match.php - 有关此方法,请参阅示例 #2。
  • http://php.net/manual/en/function.fopen.php
  • http://php.net/manual/en/function.fgets.php
  • http://php.net/trim
  • http://php.net/stripos

脚注:

  • 数据库将更容易实现这一点,并且将提供比基于文本/平面文件方法更多的自由度和灵活性。
$data = file_get_contents('filehere');
if($username == $data) { echo "User found"; } else { echo "User not found"; }

user_pass.txt:

thomas password
john password2

法典:

<?PHP
$data = fopen('user_pass.txt', 'r');
while (($line = fgets($data)) !== FALSE) {
    $data = explode(' ', $data);
    if ($username == $data[0] && $password == $data[1]) {
        echo "User found";
    } else {
        echo "User not found";
    }
}
?>

除非我错过了什么?如果您收到错误,请回复。

函数搜索:PHP 中的函数搜索

  function search($search, $string) {
    $pos = strpos($string, $search);  
    if ($pos === false) {
      echo "The string '$search' was not found.";       
    } else {
      echo "The string '$search' was found ";   
      echo "and exists at position $pos.";  
    }    
  }

爱.txt作为文件

we
love
php
programming

打开文件:

  $file = fopen("love.txt", "r");

调用函数搜索和函数 Fread 打开文件"爱.txt"

  search("love", fread($file, filesize("love.txt")));

结果:

字符串"爱"被发现并存在于位置 4。