[英]Loop through a string from file and turn values into two seperate arrays
Need a quick and easy way to turn a file, into a string I then need to turn the file into two seperate arrays called $username and $password 需要一种快速简便的方法将文件转换为字符串,然后将文件转换为两个分别称为$ username和$ password的数组
File Format: 文件格式:
user1:pass1
user2:pass2
user3:pass3
etc. I need the arrays to come out as 等。我需要数组出来
$username[0] = "user1";
$password[0] = "pass1";
$username[1] = "user2";
$password[1] = "pass2";
etc 等等
I have already read the file like this: 我已经读过这样的文件:
$file = file_get_contents("accounts.txt");
Read on explode() . 在explode()上阅读。 However, please note that when your password (or username) contains a colon, this won't work. 但是,请注意,当您的密码(或用户名)包含冒号时,此功能将无效。 You might also want to encrypt your password , and also consider using salts in encrypting passwords . 您可能还希望对密码进行加密 ,并考虑在加密密码时使用盐 。
<?php
$file = file_get_contents("accounts.txt");
$file = explode("\n",$file);
$username = array();
$password = array();
foreach ($file as $line) {
$line = explode(':',trim($line)); // trim removes \r if accounts.txt is using a Windows file format (\r\n)
$username[] = $line[0];
$password[] = $line[1];
}
do you mean: 你的意思是:
$content = file("config.txt");
$username = array();
$password = array();
foreach($content as $con) {
list($user, $pass) = explode(":", $con);
$username[] = $user;
$password[] = $pass;
}
Your array should look like this instead 您的数组应该看起来像这样
$file = file("log.txt");
$users = array();
foreach ( $file as $line ) {
list($u, $p) = explode(':', $line);
$users[] = array("user" => trim($u),"password" => trim($p));
}
var_dump($users);
Output 输出量
array (size=3)
0 =>
array (size=2)
'user' => string 'user1' (length=5)
'password' => string 'pass1' (length=5)
1 =>
array (size=2)
'user' => string 'user2' (length=5)
'password' => string 'pass2' (length=5)
2 =>
array (size=2)
'user' => string 'user3' (length=5)
'password' => string 'pass3' (length=5)
<?php
$file = "abcde:fghijkl\nmnopq:rstuvwxyz\nABCDE:FGHIJKL\n";
$reg="/([A-Za-z]{5}):([A-Za-z]+\\n)/i";
preg_match_all($reg,$file,$res);
for($i=0;$i<count($res[0]);$i++){
echo 'usename is '.$res[1][$i].'====='.'passwd is '. $res[2][$i]."<br />";
}
?>
Or you can find the split the string by finding the index of the :
: 或者,您可以通过找到:
的索引来找到分割字符串
<?php
//what you would really do
//$file = file_get_contents("accounts.txt");
//just for example
$file = "abcde:fghijkl\nmnopq:rstuvwxyz\nABCDE:FGHIJKL";
$e = explode("\n", $file);
$username = array();
$password = array();
foreach($e as $line) {
$username[] = substr($line, 0, strpos($line, ':'));
$password[] = substr($line, strpos($line, ':') + 1);
}
foreach($username as $u) {
echo $u."\n";
}
foreach($password as $p) {
echo $p."\n";
}
?>
Output 输出量
abcde
mnopq
ABCDE
fghijkl
rstuvwxyz
FGHIJKL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.