emailexp() & urlexp(): E-mail Address & URL Expanders
Last updated: 27/04/04
These functions parse e-mail addresses and URLs typed in normal text and then encloses them in appropriate anchor tags.E-mail address are completed with mailto: after href= and absolute URLs have target="_blank" to the anchor tag. If you have a content management system, online forum, message board or any Web application in which users are likely to type e-mail addresses or URLs, this function will greatly enhance the usability of user-entered data. It will parse any e-mail address or URL ending in a recognised top-level domain name, as long as they follow a space, new line, or opening parenthesis.
$pattern = "/(?<!mailto:)(\\s|^|\()(\\w+[\\w-\._]*\\w+)@(\\w+)([\\w-\._]+)*(\.)";
$pattern .= "(com|[a-z][a-z]|net|org|edu|gov|info|biz|int|mil|pro|name|aero|coop|museum)";
$pattern .= "(?!<\/a>)([^\\w]|$)(?!<\/a>|<\/A>|\")/";
$emailrep = "$1<a href=\"mailto:$2@$3$4$5$6\">$2@$3$4$5$6</a>$7";
$nemail = preg_replace($pattern, $emailrep, $email);
return $nemail;
}
function urlexp($text) {
$pattern = "/(\\s|^|\()(http:\/\/)*(\\w+)([\\w-\.]+)*(\.)";
$pattern .= "(com|[a-z][a-z]|net|org|edu|gov|info|biz|int|mil|pro|name|aero|coop|museum)";
$pattern .= "([\/?]\\w+[\\w\.\/?=-_]*\\w+)*(?!<\/a>|<\/A>|\")([^\\w]|$)(?!<\/a>|<\/A>|\")/";
$hrep = "$1<a href=\"http://$3$4$5$6$7\" target=\"_blank\">$3$4$5$6$7</a>$8";
$nt = preg_replace($pattern, $hrep, $text);
return $nt;
}
Assuming the function is saved in a file called emailexp.php and the script is included as thus: include('emailexp.php');, use the following syntax to execute the functions!
Always wrap emailexp in urlexp so the former script is run first (some surnames or usernames may be confused with top level domain names)
| e-mails and URLs: | echo urlexp(emailexp($text)); |
|---|---|
| e-mails alone: | echo emailexp($text); |
| URLs alone: | echo urlexp($text); |
Test the Script!
Type some text with an e-mail address and/or Web address!
