php - 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
解决方案
这是一个将整个文件读入数组并使用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
推荐阅读
- sql - 匹配两个没有唯一标识符的表中的人口统计数据
- sql - SQL - 显示名称而不是 ID
- aop - AspectJ 在具有匹配参数值的注释上定义切入点
- java - 要求在多线程环境中明确 TransformerFactory 的 XSLT Transformer
- ubuntu - 如何修复 Nexus 403 禁止问题
- c - 抽象结构数组
- javascript - 根据对象名称过滤对象数组
- dynamics-crm - 如何仅使用原始 TSQL 而不是 Web API 和组织服务来查询 CRM 动态实体?
- here-api - HERE Destination Weather API:我可以使用 lat/lon 代替名称吗?
- javascript - 将零移到数组的末尾并保留非零元素而不改变顺序