需要一种快速简便的方法将文件转换为字符串 然后我需要将文件转换为两个单独的数组,名为$ username和$ password
文件格式:
user1:pass1
user2:pass2
user3:pass3
等。 我需要数组出来
$username[0] = "user1";
$password[0] = "pass1";
$username[1] = "user2";
$password[1] = "pass2";
等
我已经读过这样的文件:
$file = file_get_contents("accounts.txt");
答案 0 :(得分:2)
继续阅读explode()。但是,请注意,当您的密码(或用户名)包含冒号时,这将不起作用。您可能还需要encrypt your password,还可以考虑使用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];
}
答案 1 :(得分:2)
$content = file("config.txt");
$username = array();
$password = array();
foreach($content as $con) {
list($user, $pass) = explode(":", $con);
$username[] = $user;
$password[] = $pass;
}
答案 2 :(得分:1)
你的数组应该是这样的
$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);
输出
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)
答案 3 :(得分:0)
<?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 />";
}
?>
答案 4 :(得分:0)
或者您可以通过查找:
的索引来找到拆分字符串:
<?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";
}
?>
输出
abcde
mnopq
ABCDE
fghijkl
rstuvwxyz
FGHIJKL