Skip to content

Instantly share code, notes, and snippets.

@n1k0
Created March 9, 2010 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n1k0/326744 to your computer and use it in GitHub Desktop.
Save n1k0/326744 to your computer and use it in GitHub Desktop.
Linkifies a text. Will use the `truncate_text` function of Symfony's Text helper.
<?php
/**
* Linkifies a text. Will use the `truncate_text` function of Symfony's Text helper.
*
* I'm not really proud of it, but eh, it works™.
*
* @param string $text Initial text
* @param int $maxLength Max link caption length
* @param Boolean $nofollow Add rel="nofollow" to generated links
*
* @return string
*/
function linkify($text, $maxLength = 45, $nofollow = true)
{
return preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@e',
sprintf("'<a href=\"\\1\"%s>'.truncate_text('\\1', %d).'</a>'", ($nofollow ? ' rel="nofollow"' : ''), $maxLength),
$text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment