McMaster Posted November 8, 2012 Share Posted November 8, 2012 Okay guys, On to my hated regular expressions lol. I'm having a problem here. I've been building a comment system and I want links to be converted to actual clickable URL's. I have this working but only if http:// is within the comment the user has posted. Here is my expression. return preg_replace('!(((f|ht)tp://)[-a-zA-Z?-??-?()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text); Anything I can do here so it accepts both http:// and just www (without http) Thanks in advance ATB Quote Link to comment https://forums.phpfreaks.com/topic/270455-preg_replace-url-issue/ Share on other sites More sharing options...
AyKay47 Posted November 8, 2012 Share Posted November 8, 2012 http:// is needed in links so that they are external, otherwise they will point internally which is not what we want. What you can do is write another regex that looks for www and replaces it with http://www Quote Link to comment https://forums.phpfreaks.com/topic/270455-preg_replace-url-issue/#findComment-1391064 Share on other sites More sharing options...
McMaster Posted November 8, 2012 Author Share Posted November 8, 2012 Do you know where I could find a function to do this? I'm really strugglinh here. Quote Link to comment https://forums.phpfreaks.com/topic/270455-preg_replace-url-issue/#findComment-1391074 Share on other sites More sharing options...
AyKay47 Posted November 8, 2012 Share Posted November 8, 2012 (edited) Here's a simple example for you (untested): $patterns = array('~((?:http|ftp)://(?:www)?\.[^.]+\.(?:com|org|gov))~i', '~(?<!http://)(www)\.([^.]+)\.(com|org|gov)~i'); $replace = array('<a href="$1">$1</a>', '<a href="http://$1.$2.$3">http://$1.$2.$3</a>'); $filtered_string = preg_replace($patterns, $replace, $text); The regex patterns will match 2 situations, the first will match URL's that begin with http:// or ftp:// and may possibly include www. The second will match URL's that begin with www and are not preceded by http://, it will then add http:// to the beginning of the URL to make it a valid external link. Edited November 8, 2012 by AyKay47 Quote Link to comment https://forums.phpfreaks.com/topic/270455-preg_replace-url-issue/#findComment-1391121 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.