如何解析命令行字符串来使用regex获取每个参数?

时间:2022-02-08 13:56:23

I'm working in PHP and trying to parse the information that I get from a configuration file on disk. The line looks like this:

我正在使用PHP,并试图解析从磁盘上的配置文件中获得的信息。这条线是这样的:

option ssh '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 root@example.com

选项ssh的- p443 -i /root/。ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 root@example.com

I've tried with regex or with using awk|cut under php's exec but I'm not having any success.

我尝试过regex或者在php的exec下使用awk|cut,但是没有成功。

My ideal return value looks something like this:

我的理想回报率是这样的:

    return $this->response = array(
      "host" => "example.com",
      "port" => "443",
      "user" => "root",
      "lport" => "22",
      "rport" => "2222"
    );

How do I get the arguments I need from the string with RegEx?

如何从RegEx的字符串中获得所需的参数?

1 个解决方案

#1


2  

it's not pretty and undoubtedly could be improved markedly but it more or less does what was requested, other than the 2222 ???

它并不漂亮,毫无疑问会得到显著改善,但它或多或少地满足了人们的要求,而不是2222 ?

$str="option ssh      '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 root@example.com";

$pttn='#(-p (\d{1,3}) .*:(\d+):localhost:(\d+) ((\w+)@(.*)))#';
preg_match( $pttn, $str, $matches );
$response=array( 'user'=>$matches[6], 'port'=>$matches[2], 'host'=>$matches[7], 'lport'=>$matches[4], 'rport'=>$matches[3] );


print_r( $response );

outputs:
--------
Array
(
    [user] => root
    [port] => 443
    [host] => example.com
    [lport] => 22
    [rport] => 2222
)

Like I said, not pretty but...

就像我说的,不漂亮,但是……

#1


2  

it's not pretty and undoubtedly could be improved markedly but it more or less does what was requested, other than the 2222 ???

它并不漂亮,毫无疑问会得到显著改善,但它或多或少地满足了人们的要求,而不是2222 ?

$str="option ssh      '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 root@example.com";

$pttn='#(-p (\d{1,3}) .*:(\d+):localhost:(\d+) ((\w+)@(.*)))#';
preg_match( $pttn, $str, $matches );
$response=array( 'user'=>$matches[6], 'port'=>$matches[2], 'host'=>$matches[7], 'lport'=>$matches[4], 'rport'=>$matches[3] );


print_r( $response );

outputs:
--------
Array
(
    [user] => root
    [port] => 443
    [host] => example.com
    [lport] => 22
    [rport] => 2222
)

Like I said, not pretty but...

就像我说的,不漂亮,但是……