php - 如何在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);
解决方案
我不知道你为什么调用从文件中读取的数组$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>';
推荐阅读
- visual-studio - 在 Visual Studio 中重命名文件夹后如何修复命名空间路径?
- github - 使用 GitHub 的 API 获取每次提交(在分支上)添加/删除的代码行?
- git - 如何在 Visual Studio 2019 中忽略文件夹 bin obj .vs
- r - 使用正则表达式查找最后一个周期的左侧和右侧的值并在 dplyr 中分隔
- python-3.x - 如何在使用 EOF 异常中断初始 input() 后启动新的 input() 实例?
- c++ - 在着色器内从 glOrtho 切换到 MVP 矩阵后什么都没有绘制
- python-3.x - 如何按每个数组中的第一个元素对数组数组进行冒泡排序?
- linux - 我想将一个脚本的输出通过管道传输到将独立处理第一个脚本的输出的不同脚本?
- node.js - Vuetify v-form post 不发送数据
- python - 双向 OneToOne 关系 - Django