php - 删除文件中的完全匹配

标签 php forms file match

我在这里进行了广泛搜索,但没有解决我的问题的方法(php)。

场景:用户使用预先分配的注册号码(在datafile.txt中)访问登录页面,在该字段中输入该号码时,脚本将搜索文件(如果存在)。

如果存在,请继续下一步。下一步完成后,我希望它一旦完成就自动“删除”原来使用的号码。

我相信在寻找“完全匹配”的同时,“搜索并替换”是必经之路。

我的数据文件类似于以下内容:(datafile.txt)

0
12
123
1234
12345
123456

12,如果搜索,则与123不同。

我几天前得到的一个脚本很好地完成了另一个任务:
$numbers = file_get_contents("datafile.txt");

$uNumber = $_POST['uNum'];

if ( @preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) ) {

echo "Numbers match";

}

我尝试完成一项新任务的方法如下,但没有成功:
$numbers = file_get_contents('datafile.txt', 'w+');

$uNumber = $_POST['uNum'];

if ( @preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) ) {

$numbers = preg_replace('.$_Post["uNum"]','',$numbers);

echo "Existed but will be deleted from file. ";


} else {
echo "Message showed if not in file.";
}

任何帮助将不胜感激。

最佳答案

这个怎么样:

$index = file_get_contents("datafile.txt"); 
$bodycont = str_replace("string to be replaced","what you want that string to be",$index);
$fh = fopen("datafile.txt","w");
fwrite($fh,$bodycont);
fclose($fh); 

要么:
 $file = file("datafile.txt", FILE_IGNORE_NEW_LINES);
 foreach($file as $text) {
 $test[] = $text;
 }

//get the size of the array

$arraysize = sizeof($test);

//use for loop to check if that string is found in the array and replace it

for($x=0;$x<$arraysize;$x++)
    {
               if($test[$x] == "$uNumber")
                {

                }
                else
                {
                   $newarray[] = $test[$x];
                }
    }
 $stringData = implode("\n",$newarray );
 $fh = fopen("datafile.txt","w");
 fwrite($fh,$stringData );
 fclose($fh);

这应该以某种方式工作。 :D

关于php - 删除文件中的完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10789573/

相关文章:

php - PHP 中的任意精度数学

php - 如何在AWS Elastic Beanstalk Docker容器中记录PHP错误

javascript - 禁用基于另一个字段的表单字段不起作用

javascript - 如何通过名称属性获取输入元素的集合

ruby - 关于 Ruby 中 Dir[] 和 File.join() 的混淆

php - 在 PHP 中使用 Perl CGI session

php - Laravel 聊天中的长轮询 : Why is the div not updating itself?

forms - Symfony 检查表单字段存在于 Controller 中

Python-文字游戏 "Ghost"、文件 I/O 和列表问题

c - 从二进制文件写入和读取整数数组