Right now i am using
$content = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $content);
for replacing url text with links. But, it doesn't works with + and ~ symbols in url. Can anyone figure it out what have to be done over here.
And also i want its modified version for download links which replace url text with Download.
$content = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">Download</a>', $content);
for
$fields=array('.exe','.mp3','.pdf','.rar','.doc','.jar','.ppt','.xls','.png','.jpg','.jpeg','.gif','.mp4','.avi','.mkv','.flv','.3gp','.mms','.sis','.sisx','.jad','.mdi','.qcp');
extensions.
e.g., http://www.abc.com/song1.mp3
<a href="http://www.abc.com/song1.mp3" target="_blank">Download</a>
http://www.abc.com?id=1&query=preg+replace
<a href="http://www.abc.com?id=1&query=preg+replace" target="_blank">http://www.abc.com?id=1&query=preg+replace</a>
Try this for links with + and ~:
@(https?://([-\w\.]+)+(:\d+)?((/[\w/_\.%\-+~]*)?(\?\S+)?)?)@
And this for your downloads:
@(https?://([-\w\.]+)+(:\d+)?/[\w/_\.%\-+~]+(\.exe|\.mp3|\.pdf|\.rar|\.doc|\.jar|\.ppt|\.xls|\.png|\.jpg|\.jpeg|\.gif|\.mp4|\.avi|\.mkv|\.flv|\.3gp|\.mms|\.sis|\.sisx|\.jad|\.mdi|\.qcp)(\?\S+)?)@
Here you can test them:
http://regexr.com?2vdij
http://regexr.com?2vdia
EDIT:
Now I see your problem with the link http://www.abc.com?id=1&query=preg+replace - there is a parentheses flaw in your first regexp. I have corrected my first example!
To add ~
change (https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-]*(\?\S+)?)?)?)
to (https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-~]*(\?\S+)?)?)?)
Supposed that the var $content
is a text like this:
<a href="http://somelink/" target="_blank">Download</a>
you can use this code:
$content = preg_replace('!<a href="([^\"]+)" target="_blank">[^<]+</a>!', '<a href="$1" target="_blank">$1</a>', $content);