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

读取文件并获取特定内容并回显(php),php,file-io,Php,File Io,我有一个文件(passwords_admin.txt),其中包含以下信息: # This file is for storing administrative # .passwords_user in the same directory. # # NOTE (Important): # format: <server type> <keyword>[,<keyword>...] <server name> <login name> &

我有一个文件(passwords_admin.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
...
...

有什么建议吗?

这将为您指明正确的方向:

if (preg_match("@devpw(.*)@i", $line)) {
    $data = explode (" ", $line);
    $keywords = $data[1];
    $hostname = $data[5];
}
它根据您的格式将行拆分为数组。
$hostname
设置为第六个条目,
$keywords
位于第二个条目中


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

为什么它显然不起作用?运行时出现了什么问题?它没有显示任何内容…没有错误…没有任何内容…只是空白页。好吧,您的
回送
中断
之后,因此它永远不会回送任何内容…根据此代码,它将打印匹配关键字的整行内容
devpw
。但是我想在变量中存储关键字和主机名。我用新的信息编辑了代码。但正如我告诉你的。我不要整条线。我只需要指定实例的关键字和主机名。嘿,我有个问题。您提供的代码运行良好。但是我可以避免评论吗?有没有办法检查preg_match中的两个条件?注释的定义是什么?它是在一行的开头,还是可以从任何地方开始
preg_match
允许您运行正则表达式,它可以尽可能复杂;你可以使你的一个
preg\u match
更复杂,以检查这两个条件,或者你可以调用它两次,每个条件都不同
在一行的开头。我尝试了这个
if(preg\u match(@$a(.*)@I',$line)){if(!preg\u match(“/^$comment/”,$line)){$data=explode(“,$line);$database=$data[0]$keywords=$data[1];$servername=$data[2];$password=$data[4];$hostname=$data[5];echo“$database”echo“$keywords”echo“$servername”echo“$hostname”echo”
“;}}}}
$a
有要匹配的字符串,并且
$comment
包含
,它工作正常。:)
if (preg_match("@devpw(.*)@i", $line)) {
    $data = explode (" ", $line);
    $keywords = $data[1];
    $hostname = $data[5];
}