Preg_match正则表达式,一个新行但不是两个新行,空白等


preg_match regular expression, one new line but not two new lines, whitespace, etc

我有这个文件/string:

   ----- Transcript of session follows -----
... while talking to mta6.am0.yahoodns.net.:
>>> DATA
<<< 554 delivery error: dd Sorry your message to foo@yahoo.com cannot be delivered. This account has been disabled or discontinued [#102]. - mta1070.mail.ac4.yahoo.com
554 5.0.0 Service unavailable
--p94IAEl4012027.1317751814/foo.com

   ----- Transcript of session follows -----
... while talking to mail.messaging.microsoft.com.:
>>> DATA
<<< 550 5.7.1 Service unavailable; Client host [foo] blocked using Blocklist 2, mail from IP banned; To request removal from this list please forward this message to foo@foo.com.
550 5.1.1 <foo@foo.com>... User unknown
<<< 503 5.5.2 Need rcpt command
--p94I91SC011973.1317751741/foo.com
Content-Type: message/delivery-status

我需要得到"session的transcript of session跟随——"之后的部分,直到空白的新行(或双new_line我认为)。

我试过这样做

<?php preg_match("/----- Transcript of session follows -----'n(.*)'n'n/",$email, $transcript_matches);?>

,但是不正确的,而不是.*,我可能需要any char OR new line but NOT two new lines。然后是two new lines。我怎么写呢?

谢谢。

两件事:

  • 您需要使用//s修饰符来指定.可以匹配换行符。php中regex修饰符的详细信息请参见http://php.net/manual/en/reference.pcre.pattern.modifiers.php。
  • 使用.*?指定非贪婪匹配(它将匹配它找到的最短字符串)。

把它放在一起:

<?php preg_match("/----- Transcript of session follows -----'n(.*?)'n'n/s",$email, $transcript_matches);?>

另请注意:如果您试图获得"——p94IAEl4012027.1317751814/foo.com"作为您的结果的一部分,那么请注意,它是三个新行,您正在寻找的行,而不是两个。换句话说:两个空行==三个换行符。

我能想到的另一个问题是,你正在寻找'n'n。然而,网络传输数据的断行通常是CRLF。因此,您应该为末尾出现'r做好准备:

 follows -----'s*'r?'n(.*)'r?'n'r?'n/s

您可能还想使用.*?代替.*,或者.*+