How to make any url in a string into clickable links with PHP & Linkify



Let’s say we have a string variable containing article content and there is a url but not in a link format (not in an a href tag, for example).

With Linkify function in PHP we can turn that url into a clickable link automatically. This video shows you how to use that function.

Get this “Linkify” from this GitHub page: https://gist.github.com/jasny/2000705

Watch the way we can use it in this video:

Here is the script I used in that video:

<?php


//turning all links clickable... https://gist.github.com/jasny/2000705
function linkify($value, $protocols = array('http', 'mail'), array $attributes = array())
{
	// Link attributes
	$attr = '';
	foreach ($attributes as $key => $val) {
		$attr .= ' ' . $key . '="' . htmlentities($val) . '"';
	}
	
	$links = array();
	
	// Extract existing links and tags
	$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&amp;$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);
	
	// Extract text links for each protocol
	foreach ((array)$protocols as $protocol) {
		switch ($protocol) {
			case 'http':
			case 'https':   $value = preg_replace_callback('~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i', function ($match) use ($protocol, &amp;$links, $attr) { if ($match[1]) $protocol = $match[1]; $link = $match[2] ?: $match[3]; return '<' . array_push($links, "<a $attr href=\"$protocol://$link\">$link</a>") . '>'; }, $value); break;
			case 'mail':    $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~', function ($match) use (&amp;$links, $attr) { return '<' . array_push($links, "<a $attr href=\"mailto:{$match[1]}\">{$match[1]}</a>") . '>'; }, $value); break;
			case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#](\w++)~', function ($match) use (&amp;$links, $attr) { return '<' . array_push($links, "<a $attr href=\"https://twitter.com/" . ($match[0][0] == '@' ? '' : 'search/%23') . $match[1]  . "\">{$match[0]}</a>") . '>'; }, $value); break;
			default:        $value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i', function ($match) use ($protocol, &amp;$links, $attr) { return '<' . array_push($links, "<a $attr href=\"$protocol://{$match[1]}\">{$match[1]}</a>") . '>'; }, $value); break;
		}
	}
	
	// Insert all link
	return preg_replace_callback('/<(\d+)>/', function ($match) use (&amp;$links) { return $links[$match[1] - 1]; }, $value);
}


// Now, let's try it!

echo "Without Linkify: https://google.com<br>";
echo "With Linkify: " . linkify("https://google.com");
echo "With Linkify: " . linkify("https://ciihuy.com") . " -> It's now clickable! :D";


?>
loading...

Leave a Reply

Your email address will not be published. Required fields are marked *