This preg_replace example runs through a block of text and makes hyperlinks where it finds any strings that contain "://" or "www." this is useful when you want to hyperlink [url]http://,[/url] [url]ftp://,[/url] [url]https://,[/url] file:/// etc.
It also adds email links where it finds amperands (@) embedded in text - e.g. bill@msn.com but not 12 @ $25.
I tested it very briefly before posting this so you should test it thoroughly in your application. I'm not an HTML wiz so any feedback is welcome.
It sticks http://'s in front of any www.'s that didn't have any and returns them like that.
The Clean up instruction copies the contents of $text to $ret and should be left there even if you don't need to clean it.
There is a chunk of comments in the middle that explains the Regular Expression and Replace With should you wish to modify them.
<?
print show_links("I like WWW.domcom.com, and http://www.php.net and file:///C:/temp/article.asp.htm. You can reach me at rob.self@rte.org, or bob@twofour.com");
exit;
function show_links($text){
// Clean up and transfer the target string.
$ret = preg_replace("//","",$text); // transfer (and clean source if required).
// Prefix any www. (or WWW.) strings with http:// if not already prefixed
$ret = preg_replace("/\swww./i"," http://www.",$ret); // (the i means ignore case)
// Add hrefs to strings that contain //:
$ret = preg_replace("/(\S+?:\/\/\S+?)(\s|\n|\.\s|\?\s|!|,|;|$)/","<a href=\"\$1\">\$1</a>\$2", $ret);
/*
Regular Expression - Explanation: (enclosed by "/ and /")
(\S+?:\/\/\S+?) means capture (as array element 1) any
non-whitespace characters (? means nongreedy) that follow "://",
followed by
(\s|\n|\.\s|\?\s|!|,|;|$) means capture (as array element 2) any
whitespace, newline, period followed by whitespace, question mark
followed by whitespace, exclamation, comma, semicolon or end-of-string.
Replace With - Explanation:
"<a href=\"http://\$1\">\$1</a>\$2"
means insert array element 1 between <a href=" and > and again before </a>
then restore the characters captured by array element 2
*/
// Add mailto: to strings around @'s
$ret = preg_replace("/(\S+@\S+?)(\s|\n|\. |\? |!|,|;|$)/","<a href=\"mailto:\$1\">\$1</a>\$2", $ret);
return($ret);
}
?>