I found a routine to create a html link when a link is found in a text
The characters ?=&
are for urls with query strings. Notice that I changed the separator from /
to !
because there a lot of slashes in your expression. Also note that you don't need A-Z
if you are in case-insensitive mode.
return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1">$1</a> ', $text." ");
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>
Your regex should include forward slashes in its character class for the end of the url:
/(http\:\/\/[a-zA-Z0-9_\-\.\/]*?) /i
That ought to do it.