doucheng3811 2014-07-05 06:33
浏览 271
已采纳

解析IP:来自字符串的端口,端口后面有字符#

I need a little help with this one and my RegEx knowledge is a little lacking with this one.

I have a proxy list that I'm trying to parse and separate the IP and port number from the string.

The string being read looks like this.(example 1)

121.121.121.121:8081    2.103384    Китай   high    05-07-2014 09:25:17

and sometimes look like (example 2)

222.222.222.222:8081

When I use this code.

preg_match_all('@[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}\.@',$ip,$results);
$output = (preg_split('/:/',$results));
$ip = $output['0'];
$port = $output['1'];

It works great when there is just a IP:Port like in example #2 but in example #1 its also grabbing everything past the space so the port number looks like "8081 2.103384 Китай high 05-07-2014 09:25:17"

Is there a regex pattern I can use to have it stop at a space if it see's one?

  • 写回答

3条回答 默认 最新

  • dongpao2871 2014-07-05 06:43
    关注

    With a split, you're only matching what you don't want; in this case you would want to have a match though.

    The following matching expression should work in your case:

    if (preg_match('/^(\d[\d.]+):(\d+)\b/', $proxy, $matches)) {
        $ip = $matches[1];
        $port = $matches[2];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了