Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a modified version of <a href="http://www.snipe.net/2009/09/php-twitter-clickable-links/" rel="nofollow">snipe's twitterify()</a>:</p> <pre><code>&lt;?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 // &lt;a href="www.test.com" target="_blank"&gt;hello world&lt;/a&gt; // $ret = preg_replace("#(.*?)(http://)?(www\.[^ \"\t\n\r&lt;]+)#", "&lt;a href=\"http://\\3\" target=\"_blank\"&gt;\\1&lt;/a&gt;", $ret); // if anchor text is empty, insert anchor's href $ret = preg_replace("#(&lt;a href=\"(\w+://)?([^\"]+)\"[^&gt;]+&gt;)(&lt;/a&gt;)#", "\\1\\3\\4", $ret); $ret = preg_replace("/@(\w+)/", "&lt;a href=\"http://www.twitter.com/\\1\" target=\"_blank\"&gt;@\\1&lt;/a&gt;", $ret); $ret = preg_replace("/#(\w+)/", "&lt;a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\"&gt;#\\1&lt;/a&gt;", $ret); return $ret; } </code></pre> <p>Testing the code above with <code>test()</code>...</p> <pre><code>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"); ?&gt; </code></pre> <p>...results in the following print-outs.</p> <pre><code>INPUT: "www.foo.com" OUTPUT: &lt;a href="http://www.foo.com" target="_blank"&gt;www.foo.com&lt;/a&gt; INPUT: "www.foo.com fox" OUTPUT: &lt;a href="http://www.foo.com" target="_blank"&gt;www.foo.com&lt;/a&gt; fox INPUT: "www.test.com fox jumped over www.foo.com" OUTPUT: &lt;a href="http://www.test.com" target="_blank"&gt;www.test.com&lt;/a&gt;&lt;a href="http://www.foo.com" target="_blank"&gt; fox jumped over &lt;/a&gt; INPUT: "fox jumped over www.test.com the fence www.foo.com" OUTPUT: &lt;a href="http://www.test.com" target="_blank"&gt;fox jumped over &lt;/a&gt;&lt;a href="http://www.foo.com" target="_blank"&gt; the fence &lt;/a&gt; </code></pre> <p>Tested on <a href="http://ideone.com/2eObqk" rel="nofollow">ideone</a>.</p> <p><strong>EDIT</strong>: Updated code to match new requirements</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload