Help make reg. expression.

There is a big debug text, you need to get an email in the "for" and ";" (there should be a mail inside, probably enough to check for the existence of @), the text looks like this:

Foreigners is still taking the decision on Your case. Thus today 04.10.2018, we sent a written request about the phase; for sacri.subba@yahoo.com; text text text ... for today you; other e-mail test@mai.com; 

    2 answers 2

    For email, a simplest check on the input format (presence of a dog and domain) is enough:

     "^for [a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+;$" 

    This regular line will find the line containing the fragment you need for user@example.com . Then you can make explode () of this line by the space and find the line corresponding to the mail:

     "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" 

    Empirically working solution:

     $pattern = '/for [A-Z0-9._%+-]+@[A-Z0-9.-]+\.[AZ]{2,4}\;/ui'; preg_match($pattern, $text, $res); if ($res) { $email = str_replace(';', '', explode(' ', $res[0])[1]); } 
    • I forgot to mention that there may be several e-mails in the text, and only the one that is in FOR is needed. He is alone. - mico
    • @mico made changes in response - Captain Flint
    • preg_match("/^for [a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+;$/ui", $text, $res); Returns nothing, i.e. $ res = [] - mico
    • one
      $pattern = '/for [A-Z0-9._%+-]+@[A-Z0-9.-]+\.[AZ]{2,4}\;/ui'; preg_match($pattern, $text, $res); if ($res) { $email = str_replace(';', '', explode(' ', $res[0])[1]); } $pattern = '/for [A-Z0-9._%+-]+@[A-Z0-9.-]+\.[AZ]{2,4}\;/ui'; preg_match($pattern, $text, $res); if ($res) { $email = str_replace(';', '', explode(' ', $res[0])[1]); } So it happened - mico
    • @mico added a working solution to his response - Captain Flint

    In plain text, all email addresses can be found using

     preg_match_all('~\bfor\s+\K\S+@\S+\.\S+\b~u', $s, $matches) 

    See the regular expression demo .

    Details

    • \bfor - the whole word for
    • \s+ - one or more whitespace characters
    • \K - remove all the text found so far from the match
    • \S+@\S+ - one or more characters other than whitespace, @ and again one or more characters other than whitespace
    • \. - point
    • \S+ - one or more characters other than whitespace
    • \b - word boundary.

    PHP :

     $s = <<<INPUT Foreigners is still taking the decision on Your case. Thus today 04.10.2018, we sent a written request about the phase; for sacri.subba@yahoo.com; text text text ... for today you; other e-mail test@mai.com for another###test@mai.com INPUT; if (preg_match_all('~\bfor\s+\K\S+@\S+\.\S+\b~u', $s, $matches)) { print_r($matches[0]); } 

    Result:

     Array ( [0] => sacri.subba@yahoo.com [1] => another###test@mai.com )