Github
Gist created by: f13dev
Created: June 27, 2016 - 07:15pm
Last edited: June 29, 2016 - 10:37am
Last edited: June 29, 2016 - 10:37am
Description: Converts a plain text Twitter tweet into html to <a> tags for URLs, #links and @links
Files (1)
getLinksFromTwitterText.php (0.81kb) Download file<?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;
}
Comments: 0
What does it do
This short and simple PHP function takes a plain text String as it’s input and returns rich text HTML. If any #HashTags, Twitter @UserNames or URLs are included within the input string then these are converted to clickable links to their Twitter counterpart.
Usage example
Using the getLinksFromTwitterText function
// Create a string that contains a Twitter username and a hashtag $input = "I'm @f13dev on Twitter and I like #code"; // Send the string to the getLinksFromTwitterText function getLinksFromTwitterText($input);
The above example would return:
I'm <a href="https://twitter.com/f13dev">@f13dev</a> on Twitter and I like <a href-"https://twitter.com/search?q=code">#code</a>
Or as formatted HTML: I’m @f13dev on Twitter and I like #code
Code
/** * Takes a string argument, which may include URLs, twitter #links or twitter @links, * imbeds html <a> tags into the string and returns it. * * @param String $string Plain text input * @return String $string HTML tweet with hyperlinks */ 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; }
No comments on Add #HashTag and @UserName Twitter links to plain text