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
https://forums.phpfreaks.com/topic/270455-preg_replace-url-issue/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.