Skip to content

Instantly share code, notes, and snippets.

@jasny
Last active October 21, 2023 16:28
Show Gist options
  • Star 81 You must be signed in to star a gist
  • Fork 25 You must be signed in to fork a gist
  • Save jasny/2000705 to your computer and use it in GitHub Desktop.
Save jasny/2000705 to your computer and use it in GitHub Desktop.
PHP function to turn all URLs in clickable links
<?php
/**
* Turn all URLs in clickable links.
*
* @param string $value
* @param array $protocols http/https, ftp, mail, twitter
* @param array $attributes
* @return string
*/
public 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 (&$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, &$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 (&$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 (&$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, &$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 (&$links) { return $links[$match[1] - 1]; }, $value);
}
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
@piep14
Copy link

piep14 commented Jun 3, 2019

The function does not convert multiple types of links?

Example:

a youtube link: https://www.youtube.com/embed/sJeB24OLQis and a link: https://www.brico.fr/

It sends me 2 iframes Youtube which does not make sense to me.

@habibieamrullah
Copy link

I think I'm the only dummy guy here, I don't even know how to call the "linkify" method.. is it linkify($string) ? or what?

@mhenke64
Copy link

If the URL is in parentheses (www.example.com) this code will include the trailing parenthesis in the URL giving you this (www.example.com)

I have a similar problem. When an exclamation mark appears after the url, it ads the exclamation mark to the link.

@vstelmakh
Copy link

vstelmakh commented Jul 29, 2020

have a similar problem. When an exclamation mark appears after the url, it ads the exclamation mark to the link.

@mhenke64 check out Url highlight library, it handles this and much more cases

@montrealks
Copy link

Is it possible to have a variant whereby the www part of the URL is optional?

@vstelmakh
Copy link

Solution from @MoovFun

Working sample:

<?php
function Linkify(string $value, int $img = 1, int $video = 1, array $protocols = array('http', 'mail', 'twitter', 'https'), array $attributes = array('target' => '_blank'), $video_height = 400)
{
	$attr = "";
	foreach ($attributes as $key => $val) {
		$attr .= ' ' . $key . '="' . htmlentities($val) . '"';
	}
	$links = array();
	$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);
	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, &$links, $attr, $img, $video, $video_height) {
					if ($match[1]){
						$protocol = $match[1]; $link = $match[2] ?: $match[3];
						if($video) {
							if(strpos($link, 'youtube.com') !== false || strpos($link, 'youtu.be') !== false){
								$exp = explode('=', $link);
								$ht = '<iframe width="100%" height="'.$video_height.'" src="https://www.youtube.com/embed/'.end($exp).'?rel=0&showinfo=0&color=orange&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>';
								return '<' . array_push($links, $ht) . '></a>';
							}
							if(strpos($link, 'vimeo.com') !== false){
								$exp = explode('/', $link);
								$ht = '<iframe width="100%" height="'.$video_height.'" src="https://player.vimeo.com/video/'.end($exp).'" frameborder="0" allowfullscreen></iframe>';
								return '<' . array_push($links, $ht) . '></a>';
							}
						}
						if($img) {
							if(strpos($link, '.png') !== false || strpos($link, '.jpg') !== false || strpos($link, '.jpeg') !== false || strpos($link, '.gif') !== false || strpos($link, '.bmp') !== false || strpos($link, '.webp') !== false){
								return '<' . array_push($links, "<a $attr href=\"$protocol://$link\" class=\"htmllink\"><img src=\"$protocol://$link\" class=\"htmlimg\">") . '></a>';
							}
						}
						return '<' . array_push($links, "<a $attr href=\"$protocol://$link\" class=\"htmllink\">$link</a>") . '>';
					}
			}, $value); break;
			case 'mail':    $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href=\"mailto:{$match[1]}\" class=\"htmllink\">{$match[1]}</a>") . '>'; }, $value); break;
			case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#]([\w\._]+)~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href=\"https://twitter.com/" . ($match[0][0] == '@' ? '' : 'search/%23') . $match[1]  . "\" class=\"htmllink\">{$match[0]}</a>") . '>'; }, $value); break;
			default:        $value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, "<a $attr href=\"$protocol://{$match[1]}\" class=\"htmllink\">{$match[1]}</a>") . '>'; }, $value); break;
		}
	}
	return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value);
}

use it

<?php
echo Linkify('Twitter @twitter Email boomboom@super.mail Youtube https://www.youtube.com/watch?v=1BYrHIBs6ro Vimeo https://vimeo.com/282462734 Url http://google.com Image https://www.google.pl/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png Have a nice day hohoho!!!');

Be aware, this is not working properly with urls enclosed in brackets or quotes and punctuation.

Examples:

@vstelmakh
Copy link

New solution from @MoovFun

Working sample:

function Linkify(string $value, int $img = 1, int $video = 1, array $protocols = array('http', 'mail', 'twitter', 'https'), array $attributes = array('target' => '_blank'), $video_height = 400)
{
	$attr = "";
	foreach ($attributes as $key => $val) {
		$attr .= ' ' . $key . '="' . htmlentities($val) . '"';
	}
	$links = array();
	$value = str_replace('(', '( ', $value);
	$value = str_replace(')', ' )', $value);
	$value = str_replace('"', '" ', $value);
	$value = str_replace('"', ' "', $value);
	$value = str_replace('!', ' !', $value);
	$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);
	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, &$links, $attr, $img, $video, $video_height) {
					if ($match[1]){
						$protocol = $match[1]; $link = $match[2] ?: $match[3];
						$link = str_replace([')','!','"'],'',$link);

						if($video) {
							if(strpos($link, 'youtube.com') !== false || strpos($link, 'youtu.be') !== false){
								$exp = explode('=', $link);
								$ht = '<iframe width="100%" height="'.$video_height.'" src="https://www.youtube.com/embed/'.end($exp).'?rel=0&showinfo=0&color=orange&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>';
								return '<' . array_push($links, $ht) . '></a>';
							}
							if(strpos($link, 'vimeo.com') !== false){
								$exp = explode('/', $link);
								$ht = '<iframe width="100%" height="'.$video_height.'" src="https://player.vimeo.com/video/'.end($exp).'" frameborder="0" allowfullscreen></iframe>';
								return '<' . array_push($links, $ht) . '></a>';
							}
						}
						if($img) {
							if(strpos($link, '.png') !== false || strpos($link, '.jpg') !== false || strpos($link, '.jpeg') !== false || strpos($link, '.gif') !== false || strpos($link, '.bmp') !== false || strpos($link, '.webp') !== false){
								return '<' . array_push($links, "<a $attr href=\"$protocol://$link\" class=\"htmllink\"><img src=\"$protocol://$link\" class=\"htmlimg\">") . '></a>';
							}
						}
						return '<' . array_push($links, "<a $attr href=\"$protocol://$link\" class=\"htmllink\">$link</a>") . '>';
					}
			}, $value); break;
			case 'mail':    $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href=\"mailto:{$match[1]}\" class=\"htmllink\">{$match[1]}</a>") . '>'; }, $value); break;
			case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#]([\w\._]+)~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href=\"https://twitter.com/" . ($match[0][0] == '@' ? '' : 'search/%23') . $match[1]  . "\" class=\"htmllink\">{$match[0]}</a>") . '>'; }, $value); break;
			default:        $value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, "<a $attr href=\"$protocol://{$match[1]}\" class=\"htmllink\">{$match[1]}</a>") . '>'; }, $value); break;
		}
	}
	$s = preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value);
	$s = str_replace('( ', '(', $s);
	$s = str_replace(' )', ')', $s);
	$s = str_replace('" ', '"', $s);
	$s = str_replace(' "', '"', $s);
	return str_replace(' !', '!', $s);
}

Use it

<?php
$str = '
Brackets: (http://id.iot.com)
Quotes: "http://id.iot.com"
Exclamation: http://id.iot.com!
Youtube https://www.youtube.com/watch?v=tpKCqp9CALQ
Vimeo https://vimeo.com/331653781
Url http://google.com
Image https://www.google.pl/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png
Twitter @twitter 
Email boom@super.mail!
<h2> Have a nice for all !!!</h2>
';

echo Linkify($str);

Be aware, this is still not working properly with brackets, quotes and punctuation.

Examples:

Copy link

ghost commented Oct 22, 2020

Sample:

<?php
function Linkify(string $value, int $img = 1, int $video = 1, array $protocols = array('http', 'mail', 'twitter', 'https'), array $attributes = array('target' => '_blank'), $video_height = 400)
{
	$links = array();
	$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);
	foreach ((array)$protocols as $protocol) {
		switch ($protocol) {
			case 'http':
			case 'https':
				$value = preg_replace_callback('~(?:\(?(https?)://([^\s\!]+)(?<![?,:.\"]))~i',
				function ($match) use ($protocol, &$links, $attr, $img, $video, $video_height) {
					if ($match[1]){

						$protocol = $match[1];
						$str = $match[0];
						if($str[0] === '(') { $match[2] = substr($match[2],0,-1); }
						$link = $match[2] ?: $match[3];
						if($video) {
							if(strpos($link, 'youtube.com') !== false || strpos($link, 'youtu.be') !== false){
								$exp = explode('=', $link);
								$ht = '<iframe width="100%" height="'.$video_height.'" src="https://www.youtube.com/embed/'.end($exp).'?rel=0&showinfo=0&color=orange&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>';
								return '<' . array_push($links, $ht) . '></a>';
							}
							if(strpos($link, 'vimeo.com') !== false){
								$exp = explode('/', $link);
								$ht = '<iframe width="100%" height="'.$video_height.'" src="https://player.vimeo.com/video/'.end($exp).'" frameborder="0" allowfullscreen></iframe>';
								return '<' . array_push($links, $ht) . '></a>';
							}
						}
						if($img) {
							if(strpos($link, '.png') !== false || strpos($link, '.jpg') !== false || strpos($link, '.jpeg') !== false || strpos($link, '.gif') !== false || strpos($link, '.bmp') !== false || strpos($link, '.webp') !== false){
								return '<' . array_push($links, "<a $attr href=\"$protocol://$link\" class=\"htmllink\"><img src=\"$protocol://$link\" class=\"htmlimg\">") . '></a>';
							}
						}

						if($str[0] === '(') {
							return '<' . array_push($links, "(<a $attr href=\"$protocol://$link\" class=\"htmllink\">$link</a>)") . '>';
						} else {
							return '<' . array_push($links, "<a $attr href=\"$protocol://$link\" class=\"htmllink\">$link</a>") . '>';
						}
					}
			}, $value); break;
			case 'mail':    $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href=\"mailto:{$match[1]}\" class=\"htmllink\">{$match[1]}</a>") . '>'; }, $value); break;
			case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#]([\w\._]+)~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href=\"https://twitter.com/" . ($match[0][0] == '@' ? '' : 'search/%23') . $match[1]  . "\" class=\"htmllink\">{$match[0]}</a>") . '>'; }, $value); break;
			default:        $value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, "<a $attr href=\"$protocol://{$match[1]}\" class=\"htmllink\">{$match[1]}</a>") . '>'; }, $value); break;
		}
	}
	return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value);
}

Use it:

<?php
$str = '
<a href="https://boom.doom"> Html LINK </a>
Youtube https://www.youtube.com/watch?v=tpKCqp9CALQ
Vimeo https://vimeo.com/331653781
Image https://www.google.pl/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png
Url http://google.com:
Input: Quotes "http://example.com"
Exlamation: http://example.com!
Exlamation: http://example.com?
Exlamation: http://example.com:
Exlamation: http://example.com.
Exlamation: http://example.com,
Brackets (http://example.com)
Brackets https://en.wikipedia.org/wiki/Chaquicocha_(mountain)
Twitter @twitter
Email boom@super.mail
<h2> html text </h2>
<style>.htmllink { font-weight: 900; color: #ff2255; padding: 10px; }</style>
';

echo Linkify((string) $str);

@kellyblaire1
Copy link

@MoovFun: Thanks so much for the code. It was really helpful for my project.

@fredbradley
Copy link

This is amazing. I've literally spent the last 30mins toying with preg_replace_callback to try and do this myself, and through Googleing found that someone has already done it for me!

A hero!

@S1SYPHOS
Copy link

S1SYPHOS commented Sep 9, 2021

Both solutions seem to cut off links when there are german umlauts present:

image

top: hashtag containing ä
bottom: hashtag partially detected as link, but only up to l, then cut off

Unicode characters are not supported by the regex you are using for detecting hashtags .. I therefore propose to use another regex, like this: '/#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/u' (see here)

@userofit123
Copy link

I wonder if anyone can update this to output the target destinations page title instead of outputting the links URL in the a element.

@despecial
Copy link

@userofit123 to accomplish that you'd have to query all the links and get the headers in return to change it to the desired output. If you have a lot of links the script will timeout or slow down the html output. Plus, you could be banned for sending too many server requests. So probably no one will try to add this.

@userofit123
Copy link

@userofit123 to accomplish that you'd have to query all the links and get the headers in return to change it to the desired output. If you have a lot of links the script will timeout or slow down the html output. Plus, you could be banned for sending too many server requests. So probably no one will try to add this.

Yes makes sense!

How about changing the output URL to be just the target domain rather than the full URL?

So instead of it being:
<a href="https://github.com">https://github.com</a>

It would be:
<a href="https://github.com">github.com</a>

Or
<a href="https://github.com">github</a>

@despecial
Copy link

@userofit123 on line #27 you could try to change $link output:
<a $attr href=\"$protocol://$link\">$link</a>

<a $attr href=\"$protocol://$link\">'.str_replace("www.","",$link).'</a>

(untested, just the idea)

@userofit123
Copy link

preg_replace('/^(www\.)?/i',"", parse_url($link, PHP_URL_HOST)))

That's what I ended up doing, similar to hat you suggested, thanks!
I also added the part to remove www so that it will be just the actual domain.

@S1SYPHOS
Copy link

@caspChristian .. is that even a real-world use case? Why bother with invalid formats anyway?

I don't mean to be rude, on the contrary - I'm quite interested where you got this 🦊

@NiKiZe
Copy link

NiKiZe commented Jan 28, 2022

@S1SYPHOS
In regards to: https://https://github.com
Would like to have only https://github.com since there is no port number after hostname.
Posting this as an interesting test case, of course depending on use case.

This is an example of user input, Or rather output from incorrect parsing of relative URL for redirect.
The data itself is from https://b800.org/3NynQ

@S1SYPHOS
Copy link

@NiKiZe IMHO it's the developer's responsibility to prepare input before passing it to a function, simply replace https://https with https:// yourself! The function itself should only work for 'valid' URIs .. jm2c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment