Reputation: 1207
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
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");
Upvotes: 1
Views: 285
Reputation: 19
<?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 />";
}
?>
Upvotes: 0
Reputation: 4111
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
Upvotes: 0
Reputation: 95111
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)
Upvotes: 1
Reputation: 100175
do you mean:
$content = file("config.txt");
$username = array();
$password = array();
foreach($content as $con) {
list($user, $pass) = explode(":", $con);
$username[] = $user;
$password[] = $pass;
}
Upvotes: 2
Reputation: 5389
Read on 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];
}
Upvotes: 2