Jump to content

Preg_Replace Url Issue


McMaster

Recommended Posts

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

Link to comment
Share on other sites

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 by AyKay47
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.