$re = '/(?:^|\n\n)From .*?(?:\nSubject: )([^\n]*End of shift.*?\n).*?\n\n(.*?)(?=\n\nFrom |$)/s';
$str = 'From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message 1
This is the body.
>From (should be escaped).
There are 3 lines.
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message End of shift 2
Other Headers: useless stuff
This is the second body.
Stuff
TECH
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message 2
Precedence: bulk
X-No-Archive: yes
MIME-Version: 1.0
This is the third body.
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: End of shift Sample message 2
Precedence: bulk
X-No-Archive: yes
MIME-Version: 1.0
This is the forth test.
This is the body.
>From (should be escaped).
There are 4 lights.
Lots of text
TECH
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message 4
Precedence: bulk
X-No-Archive: yes
MIME-Version: 1.0
This email is the fifth email
TECH
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php