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 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度