0

Im not too good with regular expressions, but I need a regular expression to do a mongo search in php for emails in a string like this:

[to]=>'jfields@example.com, lknight@example.com, sbeltran@example.com, ltran@example.com'

My specific problem is that I can't get a expression to work to find specifically ltran@example.com but not sbeltran@example.com.
I used something like this ['$regex'] = new MongoRegex("/(\W)(".$email.")/"); but then this doesn't find jfields@example.com because it has no space in front of it. Any help is appreciated.

Chaosjosh
  • 137
  • 1
  • 13
  • Possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Ben Harold Jan 13 '16 at 01:06
  • No it isn't, OP wants to search the `to` field for a specific address. `to` fields contains a comma/space separated list of email addresses. – Ruben Vincenten Jan 13 '16 at 01:14
  • 1
    normalize the db, you shouldn't have multiple addresses in one filed –  Jan 13 '16 at 01:19

1 Answers1

1

Use the word boundary.

$email_quoted = preg_quote($email, '#');
$regex = "#\b$email_quoted\b#";

There are three different positions that qualify as word boundaries:

  1. Before the first character in the string, if the first character is a word character.
  2. After the last character in the string, if the last character is a word character.
  3. Between two characters in the string, where one is a word character and the other is not a word character.
Ruben Vincenten
  • 807
  • 4
  • 7