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?
Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.
Definition and Usage The preg_match() function returns whether a match was found in a string.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With