我有一个具有以下结构的文本文件:
[account]
user = heinz
pwd = heinz123
description = ralf
caid = 098C,1702,1830,0B00,0D95,0648,0500,0B02,09C4
expdate = 2015-06-30
au = 1
group = 1,2,3,4,5,6,7,8,9,30
cccmaxhops = 5
cccreshare = 0
cccignorereshare = 1
[account]
user = klaus
pwd = klaus123
caid = 098C,1702,1830,0B00,0648,0D95,0500,09C4
description = sven
au = 1
betatunnel = 1833.FFFF:1702
expdate = 2015-06-30
group = 1,2,3,4,5,6,7,8,9,30
services = !xxl
cccmaxhops = 5
cccreshare = 1
cccignorereshare = 1
[account]
user = paul
pwd = paul123
description = ralf
caid = 1702,1830,0B00,0D95,0648,0500,0B02,098C
betatunnel = 1833.FFFF:1702
expdate = 2015-06-30
group = 1,2,3,4,5,6,7,8,9,30
cccmaxhops = 5
cccreshare = 0
cccignorereshare = 1
现在,例如,我需要获得"用户"字段,其中的描述是"sven"。这应该会返回"克劳斯"。你知道如何使用PHP轻松完成这个吗?每个用户块以"[account]"开头,以" cccignoereshare = 1"结尾
假设您的文件内容加载在var $content
中。这将完成工作,并为您指明从内容字符串/文件中获取其他信息的正确方向。
// Build array
$accounts = array();
$tmpAccounts = explode( "[account]", $content );
foreach ( $tmpAccounts as $data ) {
$tmpLines = explode( "'n", $data );
$parsedData = array();
foreach ( $tmpLines as $line ) {
list( $key, $value ) = explode( "=", $line );
$parsedData[trim( $key )] = trim( $value );
}
$accounts[] = $parsedData;
}
// Find 'sven' as description in array
$user = '';
foreach ( $accounts as $account ) {
if ( $account['description'] == 'sven' ) {
$user = $account['user'];
}
}
// Output
echo( $user );
另一种方法是使用某种正则表达式。但是上面的代码应该可以完成工作。