javapatriot
javapatriot

Reputation: 353

Parse message body using PHP Explode

I have the following message that I am trying to parse out of the body of the email. I am able to successfully get the email body but am running into problems pulling specific values from it. Here is an example of what the message body looks like:

John Doe just requested an service. Please see below for details: Name:John Doe Number: 8884442222 Email: [email protected]

I would like to be able to echo each of the following: John Doe 8884442222 [email protected] 123 Main St

Once I have them individually I would like to send a POST with the data. I can deal with the POST part.

Here is what im currently doing:

    $message = imap_fetchbody($connection,$email_number,1.1);
    if ($message == "") { // no attachments is the usual cause of this
        $message = imap_fetchbody($connection, $email_number, 1);
        $name = explode("Name:", $message);
        $wholename = $name[1];

        $nameExp = explode("/[\s]+/Number:", $wholename);
        $number = explode("Number:", $message);


        $nameFinal = $nameExp[0];
        $wholenumber = $number[1];

    }

//split the header array into variables
$status = ($header[0]->seen ? 'read' : 'unread');
$subject = $header[0]->subject;
$from = $header[0]->from;
$date = $header[0]->date;

echo "Whole name: " . $wholename . "<br>";
echo "Final name: " . $nameFinal . "<br>";
echo "whole number: " . $wholenumber . "<br>";

When I echo the full name I get all of the information after "Name:" (which is what is supposed to happen), same with number but when I just try to get the finalName it returns nothing. What am I missing?

Upvotes: 0

Views: 342

Answers (1)

JTinkers
JTinkers

Reputation: 1789

Just do it with plain regex, then you can access specific groups:

Name:(.+) Number: (\d+) Email:(.+) Address: (.+) Type of Property:

This will only work if the email is always in the same format - there's also missing group after 'Type of Property' but I don't know what would you write there - hopefully you get the idea.

Use https://regex101.com/ to help yourself out.

Upvotes: 4

Related Questions