1

我正在尝试从标准 Oracle 连接字符串中提取 FQDN 和端口号。我已经想出了如何单独提取 FQDN 和 PORT,但我正在寻找一个 php 正则表达式,它可以让我同时提取所有 FQDN 和 PORT。

示例连接字符串:

(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN1)(PORT=1234))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN2)(PORT=5678))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN3)(PORT=9012))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN4)(PORT=3456)))(CONNECT_DATA=(SERVICE_NAME=STUFF)))

我的预期结果将是一个数组:

[0][0] => FQDN1, [0][1] => 1234, 
[1][0] => FQDN2, [1][1] => 5678, 
[2][0] => FQDN3, [2][1] => 9012, 
[3][0] => FQDN4, [3][1] => 3456

你们的任何帮助将不胜感激。

谢谢。

4

3 回答 3

2

您可以像这样使用 preg_match_all :

if (preg_match_all('~HOST=([^)\s]+).*?PORT=([^)\s]+)~', $str, $arr))
   print_r($arr);

现场演示:http: //ideone.com/btmeao

于 2013-04-18T23:00:12.927 回答
0
$str="(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN1)(PORT=1234))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN2)(PORT=5678))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN3)(PORT=9012))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN4)(PORT=3456)))(CONNECT_DATA=(SERVICE_NAME=STUFF)))";
preg_match_all('/\(HOST=(FQDN\d)\)\(PORT=(\d+)\)/', $str, $matches, PREG_SET_ORDER);
foreach($matches as $k=>$match)
    array_shift($matches[$k]);

使用 PREG_SET_ORDER 以您想要的方式排列它们。然后 array_shift 敲掉完整的匹配。

http://ideone.com/yN07yP

只要有可能,您应该阅读文档:

http://php.net/manual/en/function.preg-match-all.php

于 2013-04-18T23:03:09.543 回答
0

尝试这个:

$subject = <<<LOD
(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN1)(PORT=1234))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN2)(PORT=5678))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN3)(PORT=9012))(ADDRESS=(PROTOCOL=TCP)(HOST=FQDN4)(PORT=3456)))(CONNECT_DATA=(SERVICE_NAME=STUFF)))
LOD;

$pattern = '~\(HOST=([^)]+)\)\(PORT=(\d+)\)~';

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);

// removes the whole match (index 0) for each result to only let the capture groups
foreach ($matches as &$match) {
    array_shift($match);
}
于 2013-04-19T00:32:06.447 回答