String Handling: Parsing Links from a String
Jul.10, 2009 in
PHP
With the popularity of APIs that connect to Twitter, Facebook, and even sites like StumbleUpon, it’s becoming increasing important to work with String Handling functions.
Here’s a very handy function to replace a link in a String with the html format for posting on the web.
I can’t remember where I got this from but someone deserves credit for helping write this:
Here’s a very handy function to replace a link in a String with the html format for posting on the web.
I can’t remember where I got this from but someone deserves credit for helping write this:
| PHP | | copy code | | ? |
| 01 | |
| 02 | function clickable_link($text) |
| 03 | {
|
| 04 | $text = preg_replace('#(script|about|applet|activex|chrome):#is', ":", $text);
|
| 05 | |
| 06 | // pad it with a space so we can match things at the start of the 1st line. |
| 07 | $ret = ' ' . $text; |
| 08 | |
| 09 | // matches an "xxxx://yyyy" URL at the start of a line, or after a space. |
| 10 | // xxxx can only be alpha characters. |
| 11 | // yyyy is anything up to the first space, newline, comma, double quote or < |
| 12 | $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "<a href="\" target="\"_blank\""></a>", $ret);
|
| 13 | |
| 14 | // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing |
| 15 | // Must contain at least 2 dots. xxxx contains either alphanum, or "-" |
| 16 | // zzzz is optional.. will contain everything up to the first space, newline, |
| 17 | // comma, double quote or <. |
| 18 | $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "<a href="\" target="\"_blank\""></a>", $ret);
|
| 19 | |
| 20 | // matches an email@domain type address at the start of a line, or after a space. |
| 21 | // Note: Only the followed chars are valid; alphanums, "-", "_" and or ".". |
| 22 | $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "<a href="\">@</a>", $ret);
|
| 23 | |
| 24 | // Remove our padding.. |
| 25 | $ret = substr($ret, 1); |
| 26 | return $ret; |
| 27 | } |
| 28 |
Comments Off













