首页 > 解决方案 > 如何在php中将文本文件读入具有2个分隔符的数组

问题描述

我正在开发一个登录服务,它接受 login.html 中的两个字段($username 和 $password)并将它们作为 post 数据传递给 login.php。我还要将一个名为“pass.txt”的文本文档读入一个数组。该文件看起来像这样。

anelhams0:7c4a8d09ca3762af61e59520943dc26494f8941b
jattenborough1:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
nmalins2:7c222fb2927d828af22f592134e8932480637c0d
dlingley3:b1b3773a05c0ed0176787a4f1574ff0075f7521e

它继续进行另外 1800 行左右。txt 文件的每一行都是一个用户名:sha1password。我将获取用户名的值并检查它是否与文本文件数组中的用户名匹配。为此,我只需要通过用户名和密码来分隔文档。因此,例如,而不是 array[0] 是 'anelhams0:7c4a8d09ca3762af61e59520943dc26494f8941b' 我需要将其分离为 array[0] = 'anelhams0' 和 array[1] = '7c4a8d09ca3762af61e59520943dc26494f8941b' 和 array[2] .我找不到任何方法来做到这一点,因为我使用了两个分隔符。有没有办法使用其他功能或循环系统来实现这一点?这就是我到目前为止在 login.php 中的内容

<?php
//Takes our username and password
$username = $_POST["username"];
$password = $_POST["password"];


//read in our text file to an array (each element is a line from the text)
$fileSort = file('pass.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

标签: phparraysfilesortingfile-handling

解决方案


我不知道你为什么调用从文件中读取的数组$fileSort。我会将其重命名为对我更有意义的名称:$allCredentials. 您需要做的就是遍历数组并在冒号上分割行。

$givenUsername = $_POST["username"];
$givenPassword = $_POST["password"];

$allCredentials = file('pass.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($allCredentials as $credentials) {
    // version 1: access credentials directly
    list($username, $password) = explode(':', $credentials);
    // version 2: or store them in a new array
    $newCredentials[] = explode(':', $credentials);
}

// here's a way to output the new array
echo '<pre>';
print_r($newCredentials);
echo '</pre>';

请参阅:foreachlist()explode()


推荐阅读