如何使用 PHP 解析包含特定字符串的文件中的一行?
使用 PHP,我想从 RIPE IP 地址范围的 whois 记录中获取以 descr:
开头的行内容,因此它们应该看起来像这样:
% 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
所以我应该得到 DAIMLER -AS 戴姆勒自治系统
结果。
如何用最少的代码做到这一点,我在 $whois 中有记录。
<?php
$whois = shell_exec('whois -h riswhois.ripe.net ' . $ip);
?>
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);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
preg_match()
来完成此操作:请注意 mutliline (
m
) 修饰符。You can accomplish this using
preg_match()
:Note the use of the mutliline (
m
) modifier.我首先将字符串拆分为行数组:
然后循环遍历它们并找到以
descr:
: 开头的字符串:或者,您知道,使用像 Tim 那样的正则表达式解决方案。
I would start by splitting the string into an array of lines:
Then loop through them and find the one that starts with
descr:
:Or, you know, use a Regex solution like Tim's.
像 Tim 这样的 preg_match 解决方案将是最佳的,但只是提出第三个建议以供参考,特别是对于较短的字符串。同样的事情可以通过以下方式完成:
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: