HMV.co.in

October 2, 2008

Regular Expressions – Url converter to hyperlinks

Filed under: php — Tags: , , , , , , , — Harsha M V @ 5:47 pm

Convert Input links in a forum to URLS

<?php

$text = "Check the web site, http://www.oreilly.co.in/hmv/
. Really kool"
;

$regex =
"{ \\b # start at word\n"
. " # boundary\n"
. "( # capture to $1\n"
. "(https?|telnet|gopher|file|wais|ftp) : \n"
. " # resource and colon\n"
. "[\\w/\\#~:.?+=&%@!\\-]+? # one or more valid\n"
. " # characters\n"
. " # but take as little as\n"
. " # possible\n"
. ")\n"
. "(?= # lookahead\n"
. "[.:?\\-]* # for possible punct\n"
. "(?:[^\\w/\\#~:.?+=&%@!\\-] # invalid character\n"
. "|$) # or end of string\n"
. ") }x";

echo preg_replace($regex, "<a href=\"$1\">$1</a>", $text);

?>

OUTPUT

Check the web site, http://www.oreilly.co.in/hmv/ . Really kool

September 23, 2008

Convert links into clickable hyperlinks

Filed under: php — Tags: , , — Harsha M V @ 10:54 pm

Description

A function to change an email address or URL into a clickable HTML hyperlink using eregi_replace.

The code


<?php

function makeClickableLinks($text) {

  $text eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',

    '<a href="\\1">\\1</a>'$text);

  $text eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',

    '\\1<a href="http://\\2">\\2</a>'$text);

  $text eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',

    '<a href="mailto:\\1">\\1</a>'$text);

return $text;

}

// Usage

// Email address example

$text "you@example.com";

echo makeClickableLinks($text);

echo "<br /><br />";

// URL example

$text "http://www.example.com";

echo makeClickableLinks($text);

echo "<br /><br />";

// FTP URL example

$text "ftp://ftp.example.com";

echo makeClickableLinks($text);

?> 

Blog at WordPress.com.