Alex Rivera | Logout

Extracting matches after colons from a predictably formatted string

Asked 2009-09-29T14:40:31.557
28

In perl regex we can extract the matched variables, ex below.

# extract hours, minutes, seconds
$time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
$hours = $1;
$minutes = $2;
$seconds = $3;

How to do this in PHP?

$subject = "E:contact@customer.com I:100955";
$pattern = "/^E:/";
if (preg_match($pattern, $subject)) {
    echo "Yes, A Match";
}

How to extract the email from there? (We can explode it and get it...but would like a method to get it directly through regex)?

Edit
Report

1 Answer

3

You can just modify your current regexp to capture everything after the colon up to the first space:

$subject = "E:contact@customer.com I:100955";
$pattern = "/^E:([^ ]+)/";
if (preg_match($pattern, $subject, $m)) {
    echo "Yes, A Match";
}
$email = $m[1];

In case you're not familiar with regexp, [^ ]+ means "any character but a space" and it doesn't require a space to be present to work. If for any reason the input changes to "E:email@host.tld" without the " I:12345" bit, it will still work.

answered 2009-09-29T14:53:22.253

Your Answer