How to parse a line out of a file that contains a certain string with PHP?
-
14-11-2019 - |
Frage
With PHP I want to get the content of the line starting with descr:
out of a whois record from RIPE IP adress ranges, so they should all look something like this:
% 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 195.66.224.97@rrc01
lastupd-last: 2012-01-25 15:18Z 203.119.76.3@rrc00
seen-at: rrc00,rrc01,rrc03,rrc04,rrc05,rrc07,rrc10,rrc11,rrc12,rrc13,rrc14,rrc15,rrc16
num-rispeers: 98
source: RISWHOIS
So I should get DAIMLER-AS Daimler Autonomous System
as a result.
How to do this with a minimum of code, I have the record in $whois.
<?php
$whois = shell_exec('whois -h riswhois.ripe.net ' . $ip);
?>
Lösung
You can accomplish this using preg_match()
:
$whois = shell_exec('whois -h riswhois.ripe.net ' . $ip);
$result = preg_match('/^descr:\s*(.+)$/m', $matches);
$descr = $matches[1];
Note the use of the mutliline (m
) modifier.
Andere Tipps
I would start by splitting the string into an array of lines:
$lines = explode("\n", $whois);
Then loop through them and find the one that starts with descr:
:
foreach($lines as $l) {
if (strpos($l, 'descr:') === 0) { //We have a winner
$description = trim(substr($l, strlen('descr:')));
}
}
Or, you know, use a Regex solution like Tim's.
A preg_match solution like Tim's would be optimal but just to put a third suggestion out there for reference and especially for shorter strings. Same thing could be accomplished with:
$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);