2012-01-25 9 views
0

私はRIPE IPアドレス範囲からのwhoisレコードのうち、descr:で始まる行の内容を取得したいので、彼らはすべて次のようになります。PHPで特定の文字列を含むファイルから行を解析するには? PHPで

% This is RIPE NCC's Routing Information Service 
% whois gateway to collected BGP Routing Tables 
% IPv4 or IPv6 address to origin prefix match 
% 
% For more information visit http://www.ripe.net/ris/riswhois.html 

route:  53.0.0.0/8 
origin:  AS31399 
descr:  DAIMLER-AS Daimler Autonomous System 
lastupd-frst: 2011-12-08 23:18Z [email protected] 
lastupd-last: 2012-01-25 15:18Z [email protected] 
seen-at:  rrc00,rrc01,rrc03,rrc04,rrc05,rrc07,rrc10,rrc11,rrc12,rrc13,rrc14,rrc15,rrc16 
num-rispeers: 98 
source:  RISWHOIS 

だから私はとしてDAIMLER-AS Daimler Autonomous Systemを取得する必要があります結果。

これを最低限のコードで実行するには、$ whoisにレコードがあります。

<?php 
$whois = shell_exec('whois -h riswhois.ripe.net ' . $ip); 
?> 
+0

whoisコマンドを実行するためにPHPからシェルを外さないでください。あなたのプログラムの中でwhoisクエリを行うか、ポート43のTCPソケットを開いて、すべての詳細についてはRFC3912を読むために、PHPに特定のライブラリがあります。 –

答えて

5

あなたはpreg_match()を使ってこれを実現することができます

$whois = shell_exec('whois -h riswhois.ripe.net ' . $ip); 
$result = preg_match('/^descr:\s*(.+)$/m', $matches); 
$descr = $matches[1]; 

注意mutliline(m)修飾子を使用します。

3

私はラインの配列に文字列を分割することから始めます:

$lines = explode("\n", $whois); 

そして、それらをループしdescr:で始まる1見つける:

foreach($lines as $l) { 
    if (strpos($l, 'descr:') === 0) { //We have a winner 
     $description = trim(substr($l, strlen('descr:'))); 
    } 
} 

それとも、あなたが知っているが、使用TimのようなRegexソリューション。

+0

+1 strpos over regex – rdlowrey

2

Tim'sのようなpreg_matchソリューションは最適ですが、参考のため、特に短い文字列のために3番目の提案を置くだけです。

$descr_starts_at = strpos($my_text,"descr:") + 14; 
$length = strpos($my_text,"lastupd-frst:") - 1 - $descr_starts_at; 

$descr = substr($my_text, $descr_starts_at ,$length); 
+0

正規表現が必要ない場合の+1。 – rdlowrey

+0

@rdlowrey:必須ではありませんが、確かに仕事がずっと楽になります。 –

+0

私はTimにも投票しましたが、私は単純な "検索"正規表現は初心者にとって理解不能または複雑すぎると思います。 – Kypros

関連する問題