Skip to content

Instantly share code, notes, and snippets.

@LaffinToo
Created December 31, 2011 07:25
Show Gist options
  • Save LaffinToo/1543238 to your computer and use it in GitHub Desktop.
Save LaffinToo/1543238 to your computer and use it in GitHub Desktop.
Twitify Links - converts twitter type text to links
<?php
// Parse Twitter nicks/lists to urls
// Internal routine
// This has a couple of functions
// TwittifyLinks() - returns True if template is set, otherwise false
// TwittifyLinks($arr,true) - $arr is a 2 element array, each holding a template for usernames/groups
// TwittifyLinks($twit) - $twit is the user/group to convert to a link
function TwittifyLinks($var=null,$set=false)
{
static $template=null;
if($set==true)
{
if(is_array($var) && count(($var)==2))
{
$template=$var;
return true;
}
return false;
}
if($set==false && $var==null)
{
return ($template!=null)?true:false;
}
if($template==null)
return false;
$type=substr($var,0,1)=='@'?0:1;
$name=strtolower(substr($var,1));
return str_replace(array('(name)','(twit)'),array($name,$var),$template[$type]);
}
// Internal
// This routine just strips the array and Twittifyes the user/group
function TwittifyReplace($matches)
{
return TwittifyLinks($matches[0]);
}
// Twittify
// $text - string to search for twit links
// $template - link template
function Twittify($text,$template=null)
{
if(($template==null && !TwittifyLinks()) || ($template!=null && !is_array($template))
|| (is_array($template) && count($template)!=2))
$template=array('<a href="/users/(name)">(twit)</a>','<a href="/group/(name)">(twit)</a>');
if($template!=null)
TwittifyLinks($template,true);
return preg_replace_callback('/(?<=^|\s)[#@][a-z0-9-_]{4,15}(?![a-z0-9-_])/ismx','TwittifyReplace',$text);
}
// Tests
$tests=array(
'hello friends, I\'m listening @daftPunk and you?',
'@Overlord, I Have no clue why ya havent died yet',
'@Gem Took her shirt off in front of @Laffin',
'@April!!!!!!!!! *HUGS* LTNS',
'@Spyke Remember to check out #Coders'
);
foreach($tests as $test)
{
echo Twittify($test). '<br>'.PHP_EOL;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment