Last active
August 29, 2015 14:01
-
-
Save jrobinsonc/e79578c41ca48bac9bde to your computer and use it in GitHub Desktop.
Linkify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* linkify | |
* | |
* @link Github: https://gist.github.com/jrobinsonc/e79578c41ca48bac9bde | |
* @param string $value | |
* @param array $protocols | |
* @param array $attributes | |
* @param string $mode | |
* @return string | |
*/ | |
function linkify($value, $protocols = array('http', 'https', 'mail', 'twitter'), $attributes = array(), $mode = 'normal') | |
{ | |
$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($mode != 'all' ? '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i' : '~([^\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($mode != 'all' ? '~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i' : '~([^\s<]+)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, '<a' . $attr . ' href="' . $protocol . '://' . $match[1] . '">' . $match[1] . '</a>') . '>'; }, $value); | |
break; | |
} | |
} | |
return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment