preg_replace与超链接有关

before I decided to post my first question on StackOverflow I turned completely crazy, so here it goes:

I've got a website that uses Google Calendar API to fetch event entries. In the description section users can fill in some details about the event. Now i'd like them to be able to put in hyperlinks. This can happen in a couple of ways. User types:

  • www.test.com
  • http(s)://test.com
  • http(s)://www.test.com
  • <a href="[one of above]" target="_blank">test.com</a>

What I'm desperately looking for is a way to convert them all to the format <a href="[http:// OR https:// OR www.]test.com" target="_blank">test.com</a>

I have already tried this syntax:

$pattern = "/(?i)\b((!<?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
$description = preg_replace($pattern, "<a href='http://$1'>$1</a>", $description);

It does change all events in the format www.test.com in a correct hyperlink, it does not change events in the format http(s)://www.test.com and http(s)://test.com. Input in the format <a href="[one of above]" target="_blank">test.com</a> becomes a mess.

Now I'm sad and tired. If someone could help me out, you're an absolute genius!

Finally solved it with a condition in PHP: here's the code so others can use it as well. Does add the path after .domain/ now.
Thanks a lot for your help!

if (!stristr($description, '<a href')){
  $pattern = "~(?:https?://)?((?:[\\p{L}\\p{N}-]+\\.)+[\\p{L}-]{2,5})((\\S)*)~m";
  $description = preg_replace($pattern, "<a href=\"$0\" target=\"_blank\">$0</a>", $description);
}

Try square brackets around the s:

$pattern = "/(?i)\b((!<?:http[s]?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";

Or:

$description = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '<a href="$1">$1</a>', $description);

You can use:

$input = preg_replace('/^(?:https?://)?((?:[\p{L}\p{N}-]+\.)+[\p{L}\p{N}-]+)\b/', 
      '<a href="http://$1" target="_blank">test.com</a>', $input);

RegEx Demo