Domanda

I have the following code which works on Online php complier

 $message1 = "The CEO is Satya Nadella On Mon, Mar 24, 2014 at 11:09 AM, wrote: > Hello ajey_teacher, > > User *ajey * has posted the following question on your course 'D' > > Question title: Who is the CEO of microsoft? > > Question description: -- Thanks, Ajey Charantimath, 973 986 4763";

 if (preg_match("/^(.*)(On (Mon|Tue|Wed|Thu|Fri|Sat|Sun).*)$/", $message1, $matches)) {
      echo "the messages are: <br>";
      print_r($matches[1]);
    }

Whereas,

This is the code I am using in Yii framework where I try to read Emails from my account, parse it and then insert it into mysql.

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox,'UNSEEN');

if($emails) {

  foreach($emails as $email_number) {

    $overview = imap_fetch_overview($inbox,$email_number,0);
    $message1 = imap_fetchbody($inbox,$email_number,1);
    $header = imap_headerinfo($inbox, $email_number);

    echo "type is---->".gettype($message1);

    echo $message1;

    if (preg_match("/^(.*)(On (Mon|Tue|Wed|Thu|Fri|Sat|Sun).*)$/", $message1, $matches)) {
      echo "the messages are: <br>";
      print_r($matches[1]);
    }
  }
}

But preg_match is not working when I fetch the message from imap_fetchbody

Initially I thought imap_fetchbody returns encoded text but when I run gettype($message1) the type of $message1 is string.

Please let me know what am I doing wrong. Basically I want to split the fetched message in the specified pattern.

Expected output after preg_match processing

The CEO is Satya Nadella
È stato utile?

Soluzione

I guess you need the multiline modifier:

if (preg_match("/^(.*)(On (Mon|Tue|Wed|Thu|Fri|Sat|Sun).*)$/s", $message1, $matches)) {
    //                                              here ___^
    echo "the messages are: <br>";
    print_r($matches[1]);
}

Also you don't all these capture group:

if (preg_match("/^(.*)On (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun).*$/s", $message1, $matches)) {
    echo "the messages are: <br>";
    print_r($matches[1]);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top