duanmu5641 2011-04-03 17:33
浏览 107
已采纳

PHP正则表达式 - 从文本块的行中获取主机名

I have a variable in PHP which holds a large text (an E-mail header to be precise).

I want to get 2 things out of this header. Here is a sample header:

Received: by mozg.ha.domain.net (Postfix, from userid 0)
    id E714C9AEDE; Tue, 29 Mar 2011 10:22:42 +0200 (CEST)
Subject: This is some text before hs34940.somedomain.tld
X-internal-Template: mozg/de/shipping.model

Now, from this text, I want to get 2 variables. One containing hs34940.somedomain.tld and the other one the 4 last digits of the number, in this case 4940. The length of the digits is variable.

I have got this currently in the variable $header, and I'd love to get $number and $name out of it.

Any help is greatly appreciated.

  • 写回答

2条回答 默认 最新

  • douna4762 2011-04-03 17:44
    关注

    Well here is a simple approach, use regular expressions one to get this line:

    Subject: This is some text before hs34940.somedomain.tld
    

    Another inside the first match to get : hs34940.somedomain.tld

    And for the number just use a substr if the number of digits is fix.

    Useful API:

    Preg_match($pattern,$match,$result) - to match patterns against text.

    substr($start_indes,$finish_index,$string) - to get a specific part of a string.


    For the Subject headline: preg_match('/Subject: [a-zA-Z0-9. ]*/', $header, $headline); For the domain: preg_match('/[a-z0-9]*[.][a-z0-9]*[.][a-z]*/', $headline[0],$domain);

    This isn't too general tho, but for your case will work just fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集