我正在使用 PHP 并尝试解析从磁盘上的配置文件中获取的信息。该行看起来像这样:
option ssh '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71031e1e05311409101c011d145f121e1c" rel="noreferrer noopener nofollow">[email protected]</a>
我尝试过使用正则表达式或使用 awk|cut在php的exec下但我没有取得任何成功。
我理想的返回值是这样的:
return $this->response = array(
"host" => "example.com",
"port" => "443",
"user" => "root",
"lport" => "22",
"rport" => "2222"
);
如何使用 RegEx 从字符串中获取所需的参数?
请您参考如下方法:
它并不漂亮,毫无疑问可以显着改进,但它或多或少符合要求,除了 2222 ???
$str="option ssh '-p 443 -i /root/.ssh/id_rsa -N -T -R 0.0.0.0:2222:localhost:22 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05776a6a7145607d64687569602b666a68" rel="noreferrer noopener nofollow">[email protected]</a>";
$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
)
就像我说的,不漂亮,但是......




