请原谅我,因为我仍然是PHP的新手。我有一个config
文件,像这样:
profile 'axisssh2'
server '110.251.223.161'
source_update 'http://myweb.com:81/profile'
file_config 'udp.group-1194-exp11nov.ovpn'
use_config 'yes'
ssh_account 'sgdo.ssh'
我想创建一个名为$currentprofile
的PHP变量,其值为axisssh2
, 值不断变化。在bash中使用grep
,我可以执行
currentprofile=$(cat config | grep ^profile | awk -F "'" '{print $2}')
但是我不知道如何用PHP做到这一点。请告诉我怎么做,谢谢。
更新:所以我尝试了preg_match
但是它只显示了1
$config=file_get_contents('/root/config');
$currentprofile=preg_match('/^profile /', $config);
echo "Current Profile: ".$currentprofile;
请告诉我出了什么事
我要冒险回答一个你没有问的问题。您最好使用parse_ini_string()或fgetcsv()。.ini
文件需要以下格式profile='axisssh2'
,因此替换空格:
$array = parse_ini_string(str_replace(' ', '=', file_get_contents($file)));
print_r($array);
收益率:
Array
(
[profile] => axisssh2
[server] => 110.251.223.161
[source_update] => http://myweb.com:81/profile
[file_config] => udp.group-1194-exp11nov.ovpn
[use_config] => yes
[ssh_account] => sgdo.ssh
)
就:
echo $array['profile'];
但是你的问题的答案应该是:
- preg_grep () preg_match ()
preg_match
返回匹配的数量(这就是为什么你得到1),但你可以得到实际的匹配与捕获组将填充第三个参数:
$config = file_get_contents('/root/config');
$currentprofile = preg_match("/^profile '(.*)'/", $config, $matches);
echo $matches[1];