Skip to content

Instantly share code, notes, and snippets.

@f13dev
Last active June 29, 2016 10:37
Show Gist options
  • Save f13dev/85ea6e90e79cad8dfe7c7cd699b13f41 to your computer and use it in GitHub Desktop.
Save f13dev/85ea6e90e79cad8dfe7c7cd699b13f41 to your computer and use it in GitHub Desktop.
Converts a plain text Twitter tweet into html to <a> tags for URLs, #links and @links
<?php
/**
* Takes a string argument, which may include URLs, twitter #links or twitter @links,
* imbeds html <a> tags into the string and returns it.
*
* @param [type] $string [description]
* @return [type] $string [description]
*/
function getLinksFromTwitterText($string)
{
// Converts a plain text url to a hyperlink
$string = preg_replace('~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i', '<a href="$0" ' . $target . ' " title="$0">$0</a>', $string);
// Converts hashtags to a link
$string = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a href=\"http://twitter.com/search?q=$1\" " . $target . " >#$1</a>", $string);
// Converts @user to a link
$string = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\" $target >@$1</a>", $string);
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment