请耐心等待,因为我对 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'
Run Code Online (Sandbox Code Playgroud)
我想创建一个名为PHP变量$currentprofile有值axisssh2,该值不断变化。随着grep在bash我可以做
currentprofile=$(cat config | grep ^profile | awk -F "'" '{print $2}')
Run Code Online (Sandbox Code Playgroud)
但我不知道如何用 PHP 做到这一点。请高手帮我如何做到这一点,谢谢。
更新:所以我尝试preg_match这样,但它只显示值1
$config=file_get_contents('/root/config');
$currentprofile=preg_match('/^profile /', $config);
echo "Current Profile: ".$currentprofile;
Run Code Online (Sandbox Code Playgroud)
请告诉我怎么了。
我要出去回答一个你没有问过的问题。你最好使用parse_ini_string()或fgetcsv()。该.ini文件需要以下格式profile='axisssh2',因此请替换空格:
$array = parse_ini_string(str_replace(' ', '=', file_get_contents($file)));
print_r($array);
Run Code Online (Sandbox Code Playgroud)
产量:
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
)
Run Code Online (Sandbox Code Playgroud)
所以就:
echo $array['profile'];
Run Code Online (Sandbox Code Playgroud)
但你的问题的答案是:
preg_match 返回匹配的数量(这就是你得到 1 的原因),但你可以使用捕获组获取实际匹配,该组将填充第三个参数:
$config = file_get_contents('/root/config');
$currentprofile = preg_match("/^profile '(.*)'/", $config, $matches);
echo $matches[1];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12356 次 |
| 最近记录: |