Search code examples
phpregexpreg-match

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: user1@somewhere.com This is just a test.. the original message was sent From: user2@abc.com";

$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?


Solution

  • 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: user1@somewhere.com This is just a test.. the original message was sent From: user2@abc.com";
    
    $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].