Lars Kaptein
Lars Kaptein

Reputation: 207

how to select a string after a certain string in php

I'm making a script that collects backup information that has been sent trough email.

Now I'm trying to get it to search for a string in the email body and then select some words behind that string.

ex. backup: successful / backup: failed

I need to get whats after the "backup:"

I tried:preg_match('/(?<=backup: )\S+/i', $output, $match); echo $match[1];

But then I get this error: Notice: Undefined offset: 1 in C:\Users\stagiair\Downloads\USBWebserver v8.5\USBWebserver v8.5\8.5\root\index.php on line 50

the code:

  <?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '**@***.**';
$password = '******';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

/* grab emails */
$emails = imap_search($inbox,'BODY "backup: geslaagd"');

/* if emails are returned, cycle through each... */
if($emails) {

    /* begin output var */
    $output = '';

    /* put the newest emails on top */
    rsort($emails);

    /* for every email... */
    foreach($emails as $email_number) {

        /* get information specific to this email */
        $overview = imap_fetch_overview($inbox,$email_number,0);
        $message = imap_fetchbody($inbox,$email_number,2);

        /* output the email header information */
        $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
        $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
        $output.= '<span class="from">'.$overview[0]->from.'</span>';
        $output.= '<span class="date">on '.$overview[0]->date.'</span>';
        $output.= '</div>';

        /* output the email body */
        $output.= '<div class="body">'.$message.'</div>';
    }

    echo $output;
    preg_match('/(?<=backup: )\S+/i', $output, $match);
    echo $match[1];

} 

/* close the connection */
imap_close($inbox);
?>

Kind regards, lars kaptein

Upvotes: 1

Views: 207

Answers (3)

huster
huster

Reputation: 67

substr(strstr($output,":"),1);

Upvotes: 0

anubhava
anubhava

Reputation: 784998

You can use following regex for preg_match call:

(?<=backup: )\w+

Live Demo: http://www.rubular.com/r/8cOLjuUOQS

Upvotes: 1

Toto
Toto

Reputation: 91385

You need to capture the group:

preg_match('/(?<=backup: )(\S+)/i', $output, $match);
//                here  __^ __^

Upvotes: 2

Related Questions