2011-06-06 141 views
0

我嘗試創建一個正則表達式來捕獲不包含aaa/bbb的.info/.con結尾的電子郵件。preg_match_all忽略單詞

這是正確的語法嗎?

Eg: // search email ending in .com/.info containing no aaa/bbb 
preg_match_all('#((?=.*@.*(?:com|info))(!.*(?:aaa|bbb)).*)#ui', $html, $emails); 

爲了得到這個:

[email protected] = no 
[email protected] = no 
[email protected] = good (address syntax correct + term absent before or after the @) 

謝謝您的答覆。

此語法正常工作SEE HERE(謝謝STEMA),除了包含空格的字符串。

e.g:

$string = "[email protected] blah [email protected] blah [email protected] [email protected]"; 
preg_match_all("#^(?!.*aaa)(?!.*bbb).*@.*\.(?:com|info)$#im", $string, $matches); 

親切

回答

1

這裏的解決方案:

#(?<=^|\s)(?![\[email protected]]*(?:aaa|bbb|(?:[0-9].*){3,}))[a-z0-9-_.]*@[a-z0-9-_.]*\.(?:com|net|org|info|biz)(?=\s|$)#im 

功能:

function get_emails($str){ 
    preg_match_all('#(?<=^|\s)(?![\[email protected]]*(?:aaa|bbb|(?:[0-9].*){3,}))[a-z0-9-_.]*@[a-z0-9-_.]*\.(?:com|net|org|info|biz)(?=\s|$)#im', $str, $output); 
    if(is_array($output[0]) && count($output[0])>0) { 
      return array_unique($output[0]); 
     } 
} 

Cor dally

1

只需使用一個積極的表達,並檢查它沒有匹配。

if (preg_match(...) == 0) 

此外,也沒有必要使用preg_match_all如果你只是有興趣的模式是否匹配與否。

+0

可能會有幾封電子郵件來捕獲並且不包含禁止使用的字詞(aaa | bbb)在HTML頁面解析。 – StackOverflowCom 2011-06-06 09:23:47

1

如果我理解您的要求正確,那麼這將是您可以與@Tomalak答案一起使用的正則表達式。

preg_match('#.*@.*(?:aaa|bbb)|\.(?:com|info)$#ui', $html, $emails); 

這種模式你想要的東西相匹配。

.*@.*(?:aaa|bbb)比賽AAA或BBB後@

\.(?:com|info)$是另一部分,這符合您的電子郵件地址與.com.info

結束後,您可以在網上看到它here on Regexr

更新:

.*(?:aaa|bbb).*\.(?:com|info)$ 

這將匹配aaabbb和字符串必須結束與.com.info

看到它在線here on Regexr

+0

謝謝你的回覆。 搜索條件可以在符號之前或之後並由字符包圍。例如:見上面 – StackOverflowCom 2011-06-06 09:18:24

+0

@la_chouette我更新了我的答案,這次我是否得到了要求? – stema 2011-06-06 09:34:51

+0

@stema首先,再次感謝您的幫助。幾乎是這樣,我也試過我的手:[HERE](http://lumadis.be/regex/test_regex.php?id=786) – StackOverflowCom 2011-06-06 09:47:17