开发者

What is the PHP regex to convert text containing a URL into a hyperlink? [duplicate]

This question already has answers here: How do I linkify urls in a string with php? (11 answers) Closed 7 years ago.

What's a regex pattern (in PHP) that replaces a string with hyperlinks, where the text preceding a URL is used as the anchor text for the link? For example:

text a http://example.com ending text

becomes

<a href="http://example.com">text a</a> ending text

In other words, the text preceding the URL becomes the anchor text for t开发者_开发百科he link.

What I really want is a variation of the following function by snipe http://www.snipe.net/2009/09/php-twitter-clickable-links/ but with the twist above.


Here's a modified version of snipe's 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;
}

Testing the code above with 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>

Tested on ideone.

EDIT: Updated code to match new requirements

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜