bash php 中等效的“grep”命令是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40135643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:19:17  来源:igfitidea点击:

What is the equivalent "grep" command in php?

phpbashawk

提问by hillz

Please bear with me since I'm still really new in PHP. So I have a configfile like this:

请耐心等待,因为我对 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'

I want to create a PHP variable named $currentprofilewith the value of axisssh2, the value keeps changing. With grepin bash I can just do

我想创建一个名为PHP变量$currentprofile有值axisssh2该值不断变化。随着grep在bash我可以做

currentprofile=$(cat config | grep ^profile | awk -F "'" '{print }')

But I have no idea how to do that with PHP. Please kindy help me how to do that, thank you.

但我不知道如何用 PHP 做到这一点。请大神帮我怎么做,谢谢。

UPDATE: So I tried preg_matchlike this but it only shows the value of 1

更新:所以我尝试preg_match这样,但它只显示值1

$config=file_get_contents('/root/config');
$currentprofile=preg_match('/^profile /', $config);
echo "Current Profile: ".$currentprofile;

Please tell me what's wrong.

请告诉我怎么了。

回答by AbraCadaver

I'm going out on a limb to answer a question that you didn't ask. You'd be better off using parse_ini_string()or fgetcsv(). The .inifile would need the following format profile='axisssh2', so replace the space:

我要出去回答一个你没有问过的问题。最好使用parse_ini_string()fgetcsv()。该.ini文件需要以下格式profile='axisssh2',因此请替换空格:

$array = parse_ini_string(str_replace(' ', '=', file_get_contents($file)));
print_r($array);

Yields:

产量:

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
)

So just:

所以就:

echo $array['profile'];

But the answer to your question would be:

但你的问题的答案是:

preg_matchreturns the number of matches (which is why you get 1) but you can get the actual matches with a capture group which will populate the third argument:

preg_match返回匹配的数量(这就是你得到 1 的原因),但你可以使用捕获组获取实际匹配,该组将填充第三个参数:

$config = file_get_contents('/root/config');
$currentprofile = preg_match("/^profile '(.*)'/", $config, $matches);
echo $matches[1];