如何在php中逐行读取文件并将其与现有字符串进行比较


How to read a file line by line in php and compare it with an existing string?

我试图编写这个程序,将文件中的用户名与输入的用户名进行比较,以检查它是否存在,但该程序似乎不起作用。请帮忙。该程序应该打开一个名为allusernames的文件来比较用户名。如果找不到用户名,请将其添加到文件中。

<?php
    $valid=1;
    $username = $_POST["username"];
    $listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
    while(!feof($listofusernames)) {
        $cmp = fgets($listofusernames);
        $val = strcmp($cmp , $username);
        if($val == 0) {
            echo ("Choose another user name, the user name you have entered has already been chosen!");
            $valid=0;
            fclose($listofusernames);
            break;
        } else {
            continue;
        }
    }
    if($valid != 0) {
        $finalusers = fopen("allusernames.txt", "a+");
        fwrite($finalusers, $username.PHP_EOL);
        fclose($finalusers);
?>

您需要替换每行中的换行符/换行符进行比较。

while(!feof($listofusernames)) {
    $cmp = fgets($listofusernames);
    $cmp = str_replace(array("'r", "'n"), '',$cmp);
    $val = strcmp($cmp , $username);
    if($val == 0) {
        echo ("Choose another user name, the user name you have entered has already been chosen!");
        $valid=0;
        fclose($listofusernames);
        break;
    } else {
        continue;
    }
}

我在你的代码中添加了以下行

  $cmp = str_replace(array("'r", "'n"), '',$cmp);

我还没有测试过,但我想知道你是否可以使用之类的东西

<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("'n",$contents);
if(in_array($user,$usernames))
{
    echo "Choose another username";
}
else
{
    $contents .= "'n".$user;
    file_put_contents("allusernames.txt",$contents);
}

我认为像文件获取内容之类的东西需要特定版本的PHP,但它们确实让事情变得更好用。

这也假定您的用户名由新行分隔。

Yo可以用以下代码更简单地完成这项工作:

<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
    echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
    $content[] = $username . PHP_EOL;
    file_put_contents($listofusernames, implode('', $content));
}
?>