GitHub
Jim Valentine
@f13dev
f13dev
Margate, UK
f13.dev
Joined March 28, 2016
Margate, UK
f13.dev
Joined March 28, 2016
Sorry, that page does not exist
Coders Rank
<?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;
}
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.
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
/** * 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; }