Without RegEx:
<?php
// take a string and turn any valid URLs into HTML links
function makelink($input) {
$parse = explode(' ', $input);
foreach ($parse as $token) {
if (parse_url($token, PHP_URL_SCHEME)) {
echo '<a href="' . $token . '">' . $token . '</a>' . PHP_EOL;
}
}
}
// sample data
$data = array(
'test one http://www.mysite.com/',
'http://www.mysite.com/page1.html test two http://www.mysite.com/page2.html',
'http://www.mysite.com/?go=page test three',
'https://www.mysite.com:8080/?go=page&test=four',
'http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive',
'ftp://test:six@ftp.mysite.com:21/pub/',
'gopher://mysite.com/test/seven'
);
// test our sample data
foreach ($data as $text) {
makelink($text);
}
?>
Output:
<a href="http://www.mysite.com/">http://www.mysite.com/</a>
<a href="http://www.mysite.com/page1.html">http://www.mysite.com/page1.html</a>
<a href="http://www.mysite.com/page2.html">http://www.mysite.com/page2.html</a>
<a href="http://www.mysite.com/?go=page">http://www.mysite.com/?go=page</a>
<a href="https://www.mysite.com:8080/?go=page&test=four">https://www.mysite.com:8080/?go=page&test=four</a>
<a href="http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive">http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive</a>
<a href="ftp://test:six@ftp.mysite.com:21/pub/">ftp://test:six@ftp.mysite.com:21/pub/</a>
<a href="gopher://mysite.com/test/seven">gopher://mysite.com/test/seven</a>