首页 > 解决方案 > PHP - 仅在 txt 文件中找到匹配项时追加

问题描述

在这里完成 php 的新手。我有一个简单的应用程序,我在其中注册不同的访问代码。我已经编写了一个函数来检查 txt 文件中的重复项,以便只附加新的唯一值。此功能工作正常,见下文。

function checkAccesscode($code)
{
    $file=fopen ("files/codes.txt", 'r');
       while ($string=fgets ($file))
      {
         if ($string!="")
            {
             $part=explode (";",$string);
             $input=trim($part[0]);

        if (stripos($input,$code)!==false)
        {
            return true;
        }
            }
        else
        {
            return false;
        }
      }
}

现在,我需要一个类似的单独函数,它还检查不同 txt 文件中的匹配项(称为“codereg.txt”)。这意味着代码不仅必须是唯一的,而且还必须在不同的应用程序/txt 文件中预先注册,然后才能附加到其文件中。

谁能指出我正确的方向?

问候, MadBer

标签: phpfunction

解决方案


这是一个将整个文件读入数组并使用preg_grep()搜索的函数。

<?php

define("UNIQ", "uniqueCodes.txt");
define("PREREQ", "preregCodes.txt");

function checkCodes(string $code):bool {

    // Quote the search string to deal with regular expression special characters

    $code = preg_quote($code,'/');

    // Read the unique file. search with preg_grep(), return false if we get back a non-empty array

    $uniq = file(UNIQ, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (preg_grep("/^{$code}/i", $uniq)) {
        return false;
    };
    
    // Read the preregistered file and search with preg_grep(). Cast the result
    // to a boolean and return. An empty array casts to FALSE, otherwise TRUE

    $preq = file(PREREQ, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    return (bool)(preg_grep("/^{$code}/i", $preq));

}

$checks = ['abc123', 'abc124', 'abc126', 'abc200'];

foreach($checks as $check) {
    echo "Checking code $check:".(checkCodes($check)?"pass":"fail")."<br>";
}

唯一代码:

abc123;first code
abc124;second code
abc125; third code

预注册代码:

abc123: a
abc124: b
abc125: c
abc200: d
abc201: e

结果:

Checking code abc123:fail  // non-unique code
Checking code abc124:fail  // non-unique code
Checking code abc126:fail  // unique, not pregistered
Checking code abc200:pass  // unique, pre-registered

推荐阅读