读取文件并获取特定内容并回显它们(php)


read file and get specific contents and echo them (php)

我有一个文件(passwords_adm.txt),其中包含以下信息:

# This file is for storing administrative
# .passwords_user in the same directory.
#
# NOTE (Important):
# format: <server type> <keyword>[,<keyword>...] <server name> <login name> <password>      
[<location> [<host> <port>] ]
# The first entry for a given server will be the default user.
# Current keywords:
# livepw - The password change script will change the sa password on this server to the 
new live password
# devpw - The password change script will change the sa password on this server to the 
new dev password
## mysql servers
##
# Do not remove the next line
# ----------- MySQL Instances start here ----------
mysql 1515,dev,devpw,online,ldap_pwd dev-exodus-01 dba_admin B66AF9 166.77.177.241 3306
mysql 1515,dev,devpw,online,ldap_pwd dev-exodus-01 dba_query 83939E 166.77.177.241 3306
mysql 1515,dev,devpw,online,ldap_pwd qa-exodus-01 dba_admin B66AF9 166.77.189.125 3306
mysql 1515,dev,devpw,online,ldap_pwd qa-exodus-01 dba_query 583939E 166.77.189.125 3306
...
...

数据存储在以下格式中:format: <server type> <keyword>[,<keyword>...] <server name> <login name> <password> [<location> [<host> <port>] ]

现在,我想复制并打印特定实例的主机名和关键字(devpw或livepw)。

例如,例如dev-exodus-01。我想打印它的主机名166.77.177.241和关键字devpw。或者有什么方法可以把这些值存储在变量中,以后可以使用它们吗?

我试过了,但显然不起作用。

$file = fopen("passwords_admin.txt", "r");
if (!$file) {
    echo "<p>Unable to open remote file.'n";
    exit;
}
while (!feof($file)) {
    $line = fgets($file, 1024);
    if (preg_match("@devpw(.*)@i", $line, $out)) {
        $title = $out[1];
        echo $title;
        echo "<br/>";
    }
}

有什么建议吗?

这应该为您指明正确的方向:

if (preg_match("@devpw(.*)@i", $line)) {
    $data = explode (" ", $line);
    $keywords = $data[1];
    $hostname = $data[5];
}

它根据您的格式将行拆分为一个数组。$hostname被设置为第六条目,并且$keywords在第二条目中。

您需要对$keywords执行类似的操作来获得单个关键字,并且您需要找到一种方法,要么只从配置文件中找到所需的一行,要么存储多行数据——一个关联数组数组可能会起作用。