Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
samjones39 Avatar asked Jul 14 '15 07:07

samjones39


People also ask

What is the return value of Preg_match () function?

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.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.

What is the difference between Preg_match and Preg_match_all?

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.

What does Preg_match mean?

Definition and Usage The preg_match() function returns whether a match was found in a string.


1 Answers

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].

like image 157
Wiktor Stribiżew Avatar answered Nov 12 '22 14:11

Wiktor Stribiżew