PHP正则表达式来过滤结果

时间:2015-09-28 13:32:42

标签: php regex

我有几个电子邮件地址的列表,如下所示

smtp:email1@myemail.com
smtp:email2@something.myemail.com
SMTP:email3@myemail.com
X400: //some random line

有什么方法我只能收到仅以myemail.com结尾的电子邮件?所以从上面来看,这将是

email1@myemail.com
email3@myemail.com

所以它应该摆脱任何随机行,如果字符串中还有其他内容,它也应该忽略它,例如东西。

我已经设法通过

获取一些数据
([a-zA-Z]+)(@)

可能不是最好的方式,但它让我知道@符号前面是什么。任何过滤这些的帮助都表示赞赏。

由于

1 个答案:

答案 0 :(得分:2)

您可能希望使用正则表达式仅过滤来自域myemail.com的电子邮件:

<?php

$emailList = <<< LOL
smtp:email1@myemail.com
smtp:email2@something.myemail.com
SMTP:email3@myemail.com
X400: //some random line
LOL;

preg_match_all('/smtp:(.*?@myemail\.com)$/im', $emailList , $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);

/*
Array
(
    [0] => email1@myemail.com
    [1] => email3@myemail.com
)
*/

<强>演示:

http://ideone.com/hcd0aa

正则表达式说明:

smtp:(.*?@myemail\.com)$

Options: Case insensitive; Exact spacing; Dot doesn’t match line breaks; ^$ don’t match at line breaks; Greedy quantifiers

Match the character string “smtp:” literally «smtp:»
Match the regex below and capture its match into backreference number 1 «(.*?@myemail\.com)»
   Match any single character that is NOT a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match the character string “@myemail” literally «@myemail»
   Match the character “.” literally «\.»
   Match the character string “com” literally «com»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»