Link to home
Start Free TrialLog in
Avatar of rgb192
rgb192Flag for United States of America

asked on

creating a function from a regex and returning two parts

this question is about creating a function from question
https://www.experts-exchange.com/questions/27998518/want-only-the-email-address-from-email.html


$email = " Ray <ray.paseur@gmail.com>"

// A REGULAR EXPRESSION TO FIND THE FROM-EMAIL ADDRESS
$regex
= '#'         //REGEX DELIMITER
. '.*?'       // ANYTHING OR NOTHING
. '\<'        // ESCAPED WICKET
. '(.*?)'     // GROUP OF CHARACTERS WITH EMAIL ADDRESS
. '\>'        // ESCAPED WICKET
. '#'         // REGEX DELIMITER
;


// ISOLATE THE FROM EMAIL ADDRESS
preg_match($regex, $email, $matches);
$from = $matches[1];

Open in new window





function emailregex(){
// A REGULAR EXPRESSION TO FIND THE FROM-EMAIL ADDRESS
$regex
= '#'         //REGEX DELIMITER
. '.*?'       // ANYTHING OR NOTHING
. '\<'        // ESCAPED WICKET
. '(.*?)'     // GROUP OF CHARACTERS WITH EMAIL ADDRESS
. '\>'        // ESCAPED WICKET
. '#'         // REGEX DELIMITER
;


// ISOLATE THE FROM EMAIL ADDRESS
preg_match($regex, " Ray <ray.paseur@gmail.com>" , $matches);
return $matches;
}

Open in new window



i need to use $matches[0] and $matches[1]
Avatar of kaufmed
kaufmed
Flag of United States of America image

What do you mean by, "i need to use $matches[0] and $matches[1]?" $matches[0] should be the whole match, and $matches[1] should be just the first capture group (the stuff between the brackets in this case). Are you wanting to do something like:

return array($matches[0], $matches[1]);

Open in new window

Avatar of rgb192

ASKER

when I test
$matches[0] is the name 'ray'
and
$matches[1] is the email
Avatar of rgb192

ASKER

if I do

return array($matches[0], $matches[1]);

I dont know how to call and echo
array($matches[0], $matches[1])
Are you referring to?

$result = emailregex();

echo $result[0];
echo $result[1];

Open in new window

$result = emailregex();
echo $result[0];
echo $result[1];
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

Ray's code take the parameter. So it works for me.

I cant understand how to do an empty function() with this

thanks
Not sure I understand empty function() either, but thanks for the points.  You might consider something like this...

function emailregex($str=FALSE)
{
    if (!$str) return array();
    /* etc */...

Open in new window

Well, I'm certainly glad that question was clear  : \
@kaufmed: Me too.