Extract emails from a string

Language:: PHP Type::snippet Back-end

Description:: Ever wondered how spammers can get your email address? That’s simple, they get web pages (such as forums) and simply parse the html to extract emails. This code takes a string as a parameter, and will print all emails contained within. Please don’t use this code for spam ;)

`01.``function`  `extract_emails(``$str``){`
`02.``// This regular expression extracts all emails from a string:`
 
`03.``$regexp`  `= ``'/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'``;`
 
`04.``preg_match_all(``$regexp``, ``$str``, ``$m``);`
`05.`
`06.``return`  `isset(``$m``[0]) ? ``$m``[0] : ``array``();`
`07.``}`
`08.`
`09.``$test_string`  `= 'This is a test string...`
`10.`
`11.``test1@example.org`
`12.`
`13.``Test different formats:`
`14.``test2@example.org;`
`15.``<a href=``"test3@example.org"``>foobar</a>`
`16.``<test4@example.org>`
`17.`
`18.``strange formats:`
`19.``test5@example.org`
`20.``test6[at]example.org`
`21.``test7@example.net.org.com`
`22.``test8@ example.org`
`23.``test9@!foo!.org`
`24.`
`25.``foobar`
`26.``';`
`27.`
`28.``print_r(extract_emails(``$test_string``));`

Source: http://www.jonasjohn.de/snippets/php/extract-emails.htm