Sunday, January 7, 2018

Convert URL To Clickable Link Using PHP

This post explains how to Convert URL To Clickable Link Using PHP. Here I am using below PHP function to turn all URLs in clickable links with the help of Regular Expression validation.


lets see the user defined PHP Function which convert URL to Clickable Link.

convertLink.php
This function covert URL to Link with the help of Regular Expression validation.

 <?php
function Convert_link_to_urls($text = '')
{
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
$finaltext = ' ' . $text;
$finaltext = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<span class='ccc'><a href=\"\\2\" target=\"_blank\"><font style='font-family: Verdana, Geneva, sans-serif;color: blue;font-size:13px; line-height:20px;'>\\2</font></a></span>", $finaltext);
$finaltext = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<span class='ccc'><a href=\"http://\\2\" target=\"_blank\"><font style='font-family: Verdana, Geneva, sans-serif;color: blue;font-size:13px; line-height:20px;'>\\2</font></a></span>", $finaltext);
$finaltext = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<span class='ccc'><a href=\"mailto:\\2@\\3\"><font style='font-family: Verdana, Geneva, sans-serif;color: blue;font-size:13px; line-height:20px;'>\\2@\\3</font></a></span>", $finaltext);
$finaltext = substr($finaltext, 1);
return $finaltext;
}
?>

Index.php
Here we are calling Convert_link_to_urls  Function to display the clickable Link:

<?php
include('convertLink.php');

$text='welcome to skptricks : http://www.skptricks.com/2017/12/download-urls-content-using-php-curl.html';

echo Convert_link_to_urls($text);

?>


No comments:

Post a Comment