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

时间:2015-03-23 15:21:53

标签: php string file search

我尝试编写此程序来比较文件中的用户名和输入的用户名,以检查它是否存在,但程序似乎不起作用。请帮忙。该程序应该打开一个名为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);
?>

3 个答案:

答案 0 :(得分:3)

您需要从每行替换换行符/换行符以进行比较。

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);

答案 1 :(得分:1)

我没有测试过这个,但我想知道你是否可以使用像

这样的东西
<?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,但它们确实使得工作更好。

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

答案 2 :(得分:0)

使用此代码,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));
}

?>