Skip to content

Instantly share code, notes, and snippets.

@clemherreman
Created November 23, 2012 15:09
Show Gist options
  • Save clemherreman/4136059 to your computer and use it in GitHub Desktop.
Save clemherreman/4136059 to your computer and use it in GitHub Desktop.
Turn url to clickable links © symfony 1.4
<?php
if (!defined('SF_AUTO_LINK_RE'))
{
define('SF_AUTO_LINK_RE', '~
( # leading text
<\w+.*?>| # leading HTML tag, or
[^=!:\'"/]| # leading punctuation, or
^ # beginning of line
)
(
(?:https?://)| # protocol spec, or
(?:www\.) # www.*
)
(
[-\w]+ # subdomain or domain
(?:\.[-\w]+)* # remaining subdomains or domain
(?::\d+)? # port
(?:/(?:(?:[\~\w\+%-]|(?:[,.;:][^\s$]))+)?)* # path
(?:\?[\w\+%&=.;-]+)? # query string
(?:\#[\w\-/\?!=]*)? # trailing anchor
)
([[:punct:]]|\s|<|$) # trailing text
~x');
}
/**
* Turns all urls into clickable links.
*/
function _auto_link_urls($text, $href_options = array(), $truncate = false, $truncate_len = 40, $pad = '...')
{
$href_options = _tag_options($href_options);
$callback_function = '
if (preg_match("/<a\s/i", $matches[1]))
{
return $matches[0];
}
';
if ($truncate)
{
$callback_function .= '
else if (strlen($matches[2].$matches[3]) > '.$truncate_len.')
{
return $matches[1].\'<a href="\'.($matches[2] == "www." ? "http://www." : $matches[2]).$matches[3].\'"'.$href_options.'>\'.substr($matches[2].$matches[3], 0, '.$truncate_len.').\''.$pad.'</a>\'.$matches[4];
}
';
}
$callback_function .= '
else
{
return $matches[1].\'<a href="\'.($matches[2] == "www." ? "http://www." : $matches[2]).$matches[3].\'"'.$href_options.'>\'.$matches[2].$matches[3].\'</a>\'.$matches[4];
}
';
return preg_replace_callback(
SF_AUTO_LINK_RE,
create_function('$matches', $callback_function),
$text
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment