New line Email not getting using regular expression

Viewed 65

Firstly, I tried all the questions & answers related to this topic. Additionally and I tried related questions and try to solve them but no success. So please read my question thoroughly.

Problem: Can not get "Lucy 3" email on Array.

I want to all Email stores category-wise (To / CC / BC /BCC ). I am getting an Email header and using a regular expression filter email. it's working fine. but in case To or From any email add a new line so the new line email is not getting on my Array.

Demo link Here

Code

$String_Header = 'From support@test.co.uk  Wed Nov 20 15:48:00 2013
Return-Path: <support@test.co.uk>
X-Original-To: mailbox@my.domain.com
Delivered-To: mailbox@my.domain.com
Delivered-To: techinfo@test.co.uk
from: "Lucy 1" <support@lucky1.co.uk>,"Lucy 2" <support@lucky2.co.uk>,
"Lucy 3" <support@lucky3.co.uk>
to: TestTo <techinfo@test.co.uk>';

function ProcessTicketPostHeaders($headers)
{
    if (is_string($headers)) {
        $_headersWeWantToKeep = array("from", "to", "cc", "bcc");
         $headers = preg_replace('/\r?\n /', ' ', $headers);        
        $_pattern = '/^(' . implode('|', $_headersWeWantToKeep) . '):.*$/im';       
        if (preg_match_all($_pattern, $headers, $headers)) {                
            $headers = implode("\n", $headers[0]);
        }
    }
 
    return $headers;
}

echo '<pre>';
print_r(ProcessTicketPostHeaders($String_Header));

OutPut:

from: "Lucy 1" ,"Lucy 2" ,
to: TestTo

I want Output:

from: "Lucy 1" ,"Lucy 2"  ,"Lucy 3"
to: TestTo
1 Answers

You could match all lines that do not start with any of the values in $_headersWeWantToKeep or an empty line if you don't want to match all that followed after the last match.

The full pattern could look like

^(from|to|cc|bcc):.*(?:\R(?!(?:(?1)|$)).*)*

Regex demo | Php demo

For example

$String_Header = 'From support@test.co.uk  Wed Nov 20 15:48:00 2013
Return-Path: <support@test.co.uk>
X-Original-To: mailbox@my.domain.com
Delivered-To: mailbox@my.domain.com
Delivered-To: techinfo@test.co.uk
from: "Lucy 1" <support@lucky1.co.uk>,"Lucy 2" <support@lucky2.co.uk>,
"Lucy 3" <support@lucky3.co.uk>
to: TestTo <techinfo@test.co.uk>';

function ProcessTicketPostHeaders($headers)
{
    if (is_string($headers)) {
        $_headersWeWantToKeep = array("from", "to", "cc", "bcc");
        $headers = preg_replace('/\r?\n /', ' ', $headers);
        $_pattern = '/^(' . implode('|', $_headersWeWantToKeep) . '):.*(?:\R(?!(?:(?1)|$)).*)*/m';
        if (preg_match_all($_pattern, $headers, $headers)) {
            $headers = implode("\n", $headers[0]);
        }
    }

    return $headers;
}

echo '<pre>';
print_r(ProcessTicketPostHeaders($String_Header));

Output

<pre>from: "Lucy 1" <support@lucky1.co.uk>,"Lucy 2" <support@lucky2.co.uk>,
"Lucy 3" <support@lucky3.co.uk>
to: TestTo <techinfo@test.co.uk>
Related