Linkify text into Clickable Hyperlinks

Are you surprised of seeing URLs on the #Facebook or #Twitter or on Gmail when you typed or composed a content containing some text along with urls in it….??

Did you ever try of doing that???

Today i will show you how to do that thing in a simple but efficient way in about 6 lines of Code…

<?php
function autolink($string)
{
$content_array = explode(” “, $string);
$output = ”;

foreach($content_array as $content)
{
if(substr($content, 0, 7) == “http://“)
$content = ‘<a href=”‘ . $content . ‘”>’ . $content . ‘</a>’;
if(substr($content, 0, 4) == “www.”)
$content = ‘<a href=”http://‘ . $content . ‘”>’ . $content .'</a>’;

$output .= ” ” . $content;
}

$output = trim($output);
return $output;
}
?>

To use this function just call it on buttom click or during inserting into database….
<?php
echo autolink(“Hello I’m Krishna Manoj..my website is
https://kmvkrish.wordpress.com“);
?>

An example code for using the same is….

<?php

if(isset($_POST[‘url’]))

{

$url = $_POST[‘url’];

autolink($url);

}

function autolink($string)
{
$content_array = explode(” “, $string);
$output = ”;

foreach($content_array as $content)
{
if(substr($content, 0, 7) == “http://”)
$content = ‘<a href=”‘ . $content . ‘”>’ . $content . ‘</a>’;
if(substr($content, 0, 4) == “www.”)
$content = ‘<a href=”http://’ . $content . ‘”>’ . $content .'</a>’;

$output .= ” ” . $content;
}

$output = trim($output);
return $output;
}

?>
<html>
    <body>
        <form method=”post” action=””>
<input type=”text” name=”urlplaceholder=”enter url… size=”120″>
<input type=”submit” value=”Linkifyname=”submit“>
</form>
    </body>
</html>

Explanation…

First retrieve the text entered by the user….

Divide the text based on a delimiter into array…(Explode function dvides the text into array)

for every variable in the array check for http:// or www. values in the array values…

if present display them using <a> tag…else display them as plain text…

Thats it!!..its very simple..Have a good day…

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s