0

I've created a message system and would like to auto-convert url-links in a message to clickable HTML links if a new message is posted. I wrote this simple function but it isn't working as it should:

    // LINK ALL URLS
  $message = ereg_replace("http://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $message);
  $message = ereg_replace("(^| |\n)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $message);

For some urls it is working, but with other urls there are problems and the results are like this:

<a href="http://www.example.com/index.php">http://www.example.com/index.php</a>?mode=index&page=1

or

<a href="http://www.youtube.com/watch">http://www.youtube.com/watch</a>?v=jSh5Y7jq9FQ

As you can see, it is not correctly converted inclusive the part behind the question mark. Can someone please fix / update my code above? And by the way, would there be perhaps another (and better!) solution instead of using *ereg_replace* ?

4

3 回答 3

2

这是我现在使用的解决方案,它似乎工作正常,包括问号修复和注释中将 ereg_replace() 转换为 preg_replace() 的建议:

// LINK ALL URLS
      $message = preg_replace("#http://([.]?[a-zA-Z0-9_/-?])*#", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $message);
      $message = preg_replace("#(^| |\n)(www([.]?[a-zA-Z0-9_/-?])*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $message);
于 2013-06-17T13:31:16.123 回答
2
 $message = preg_replace('#((?:[a-zA-Z]+://|www)[^ ]+)#i', '<a href="$0">$0</a>', $message);

这可能会帮助你

于 2013-06-17T12:58:16.387 回答
1

您的正则表达式不允许该?字符,因此链接当然会在任何查询字符串之前切断。放入?你的角色类。当您使用它时,您还需要允许每个其他有效的 URL 字符。

请参阅此问题及其答案,了解是什么构成了有效的 URL 正则表达式。

于 2013-06-17T12:30:41.023 回答