2

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:

option ssh '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 [email protected]

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

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?

3
  • This format is fixed it never changes ? Commented Jan 24, 2016 at 23:14
  • That isn't a trivial string to parse, and the solution depends on whether you want to check it for validity, or simply parse it for the fields you want. You should look at preg_split Commented Jan 24, 2016 at 23:14
  • 2
    I think you should look at getopt as it looks like you're parsing command line input Commented Jan 24, 2016 at 23:17

1 Answer 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 ???

$str="option ssh      '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 [email protected]";

$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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.