View Full Version : Hyperlink URLS

Deacon Frost
01-09-2010, 01:19 PM
I've got this function:

/* clickable($url) changes a block of text to use urls */
function clickable($url){
$in = array('`((?:https?|ftp)://\S+[[:alnum:]]/?)`si','`((?<!//)(www\.\S+[[:alnum:]]/?))`si');
$out = array('<a href="$1" rel="nofollow" target="_blank">$1</a>', '<a href="http://$1" rel="nofollow" target="_blank">$1</a>');
return preg_replace($in,$out,$url);

And, I just tried it out with a series of other functions, and it went haywire. I don't understand regex yet, so help is appreciated ^.^.

Here's the context I'm using it in:

/* escape_data($string) This function cleans data for databases. */

function escape_data ($data) {
if (ini_get('magic_quotes_gpc')) {
$data = stripslashes($data);
$data = mysql_escape_string (trim($data));
return $data;

/* format_string($str) fixes a string for input and display */
function format_string($str) {
$string = escape_data($str);
$string = str_replace("\n", "<br />", $string);
$string = clickable($string);
return $string;

echo format_string($input);

The problem I was having was rather odd. The hyperlink linked multiple url strings with 1 anchor. But it did that twice. The format_string function also failed to replace '\n' with '<br />' in the instance when I used clickable(). It's never done that before, though =/.

01-09-2010, 03:55 PM
If you're working with URL's, I highly recommend using parse_url() (http://www.php.net/parse_url) instead of a regex