1

需要一种快速简便的方法将文件转换为字符串,然后我需要将文件转换为两个单独的数组,称为 $username 和 $password

文件格式:

user1:pass1
user2:pass2
user3:pass3

等我需要阵列出来

$username[0] = "user1";
$password[0] = "pass1";

$username[1] = "user2";
$password[1] = "pass2";

ETC

我已经读过这样的文件:

$file = file_get_contents("accounts.txt");
4

5 回答 5

2

阅读explode()。但是,请注意,当您的密码(或用户名)包含冒号时,这将不起作用。您可能还想加密您的密码,并考虑在加密密码时使用盐

<?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];
}
于 2012-11-11T08:44:51.930 回答
2

你的意思是:

$content = file("config.txt");
$username = array();
$password = array();

foreach($content as $con) {
  list($user, $pass) = explode(":", $con);
  $username[] = $user;
  $password[] = $pass;

}
于 2012-11-11T08:45:08.933 回答
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)
于 2012-11-11T08:49:07.490 回答
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 />";
}

?>
于 2012-11-11T08:48:24.360 回答
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
于 2012-11-11T08:51:54.050 回答