1

I am trying to obtain the local part of an email ID using regex. The challenge here is that the local part comes in two different formats and I need to figure out which format I'm reading and prepare the alternate form of that email ID. As always the snippet of my code that does this is pasted below.

$testarray = array("[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]");

foreach($testarray as $emailID) {
  preg_match("/([\w\d]*)\.([\w\d]*)@gmail.com/", $emailID, $match);

  if ($match[2] == "tp") {
    $altform = $match[1] . "@gmail.com";
  } else {
    $altform = $match[1] . "[email protected]";
  }

  error_log("ALTERNATE FORM OF $emailID IS $altform");

}

The problem I'm facing here is I'm not getting the desired result as neither $match[1] and $match[2] match anything for "[email protected]".

2
  • Please share the desired result Commented Mar 23, 2017 at 5:12
  • Your regular expression is expecting a full stop \. character, you should test if preg_match() actually worked or not before trying to consume $match Commented Mar 23, 2017 at 5:21

1 Answer 1

1

You need to use an optional group around the dot + word chars subpattern, and then check if the group matched after executing the search:

foreach($testarray as $emailID) {
    $altform = "";
    if (preg_match("/(\w+)(?:\.(\w+))?@gmail\.com/", $emailID, $match))
    {
        if (!empty($match[2]) && $match[2] == "tp") {
            $altform = $match[1] . "@gmail.com";
        } else {
            $altform = $match[1] . "[email protected]";
        }
    }
    print_r("ALTERNATE FORM OF $emailID IS $altform\n");
}

See the online PHP demo.

Notes on the pattern:

  • (\w+) - Capturing group 1: one or more word chars
  • (?:\.(\w+))? - 1 or 0 occurrences (due to ? quantifier) of:
    • \. - a dot
    • (\w+) - Capturing group 2: one or more word chars
  • @gmail\.com - a literal string @gmail.com (note the . is escaped to match a literal dot).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.