Given the following examples, I want to get the email address
Eg. 1: some standard text. Bugs Bunny bugs@gmail.com 0411111111 more standard text
Eg. 2: some standard text. Bugs The Bunny bugs@gmail.com 0411111111 more standard text
Eg. 3: some standard text. Bugs-Bunny bugs.bunny@gmail.com 0411111111 more standard text
Eg. 4: some standard text. Bugs bugs.bunny@gmail.com +6141 111 111 more standard text
Eg. 5: some standard text. Bugs o'Bunny bugs@gmail.com 0411111111 more standard text
This will do it: (?<=some standard text. )(?:.*?)([^\s]+@[^\s]+)
https://regex101.com/r/A29hjE/9
But the email address is in group 1. I need it to be group 0 or the full match because this regex will be created dynamically by some code in which all other regex's produce their findings as the full match.
I don't know enough about groups, but I know I need the first email address after the some standard text.
bit and, like I said, it need's to be the full match.
If you change your regex to simply be ([^\s]+@[^\s]+), the full result should be just the email address.
Group 0 is the full match.
If you change your regex to just be [^\s]+@[^\s]+
then it will match the email address in all your examples. https://regex101.com/r/SQL9Ul/1
Because of the varying length of the name, you cannot use a positive lookbehind and match the email address as the whole match.
You could do:
$lines = array(
"some standard text. Bugs Bunny bugs@gmail.com 0411111111 more standard text ",
"some standard text. Bugs The Bunny bugs@gmail.com 0411111111 more standard text",
"some standard text. Bugs-Bunny bugs.bunny@gmail.com 0411111111 more standard text",
"some standard text. Bugs bugs.bunny@gmail.com +6141 111 111 more standard text",
"some standard text. Bugs o'Bunny bugs@gmail.com 0411111111 more standard text ",
);
foreach($lines as $line) {
preg_match('/some standard text..+?\K\S+@\S+/', $line, $m);
var_dump($m);
}
where:
\K
means forget all we have encountered until here.\S
stands for any NON whitespace, it's the same that [^\s]
Then we have only the email in $m[0]
Output:
array(1) {
[0]=>
string(14) "bugs@gmail.com"
}
array(1) {
[0]=>
string(14) "bugs@gmail.com"
}
array(1) {
[0]=>
string(20) "bugs.bunny@gmail.com"
}
array(1) {
[0]=>
string(20) "bugs.bunny@gmail.com"
}
array(1) {
[0]=>
string(14) "bugs@gmail.com"
}