且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是PHP正则表达式,可以将包含URL的文本转换为超链接?

更新时间:2022-04-02 22:39:42

这是狙击的twitterify():

<?php
function twitterify($ret) {
  //
  // Replace all text that precedes a URL with an HTML anchor
  // that hyperlinks the URL and shows the preceding text as
  // the anchor text.
  // 
  // e.g., "hello world www.test.com" becomes
  // <a href="www.test.com" target="_blank">hello world</a>
  //
  $ret = preg_replace("#(.*?)(http://)?(www\.[^ \"\t\n\r<]+)#", "<a href=\"http://\\3\" target=\"_blank\">\\1</a>", $ret);

  // if anchor text is empty, insert anchor's href
  $ret = preg_replace("#(<a href=\"(\w+://)?([^\"]+)\"[^>]+>)(</a>)#", "\\1\\3\\4", $ret);

  $ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
  $ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
  return $ret;
}

使用test() ...

function test($str) {
  print "INPUT:  \"" . $str . "\"\nOUTPUT: " . twitterify($str) . "\n\n";
}
// tests
test("www.foo.com");
test("www.foo.com  fox");
test("www.test.com  fox jumped over  www.foo.com");
test("fox jumped over  www.test.com   the fence   www.foo.com");
?>

...导致以下打印输出.

...results in the following print-outs.

INPUT:  "www.foo.com"
OUTPUT: <a href="http://www.foo.com" target="_blank">www.foo.com</a>

INPUT:  "www.foo.com  fox"
OUTPUT: <a href="http://www.foo.com" target="_blank">www.foo.com</a>  fox

INPUT:  "www.test.com  fox jumped over  www.foo.com"
OUTPUT: <a href="http://www.test.com" target="_blank">www.test.com</a><a href="http://www.foo.com" target="_blank">  fox jumped over  </a>

INPUT:  "fox jumped over  www.test.com   the fence   www.foo.com"
OUTPUT: <a href="http://www.test.com" target="_blank">fox jumped over  </a><a href="http://www.foo.com" target="_blank">   the fence   </a>

ideone 上进行了测试.

编辑:已更新代码以符合新要求

EDIT: Updated code to match new requirements