samjones39
samjones39

Reputation: 163

How to preg_match first occurrence in a string

I am trying to extract From:address from an email body. Here is what I have so far:

$string = "From: [email protected] This is just a test.. the original message was sent From: [email protected]";

$regExp = "/(From:)(.*)/";
$outputArray = array();
if ( preg_match($regExp, $string, $outputArray) ) {
print "$outputArray[2]";
}

I would like to get the email address of the first occurrence of From: .. any suggestions?

Upvotes: 5

Views: 5770

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626871

Your regex is too greedy: .* matches any 0 or more characters other than a newline, as many as possible. Also, there is no point in using capturing groups around literal values, it creates an unnecessary overhead.

Use the following regular expression:

^From:\s*(\S+)

The ^ makes sure we start searching from the beginning of the string,From: matches the sequence of characters literally, \s* matches optional spaces, (\S+) captures 1 or more non-whitespace symbols.

See sample code:

<?php
$string = "From: [email protected] This is just a test.. the original message was sent From: [email protected]";

$regExp = "/^From:\s*(\S+)/";
$outputArray = array();
if ( preg_match($regExp, $string, $outputArray) ) {
print_r($outputArray[1]);
}

The value you are looking for is inside $outputArray[1].

Upvotes: 5

Related Questions