Add #HashTag and @UserName Twitter links to plain text


[f13gist gid=”85ea6e90e79cad8dfe7c7cd699b13f41″]

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

The above example would return:

I'm <a href="">@f13dev</a> on Twitter and I like <a href-"">#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=\"$1\" " . $target . " >#$1</a>", $string);
    // Converts @user to a link
    $string = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"$1\" $target >@$1</a>", $string);
    return $string;

3 tags for "Add #HashTag and @UserName Twitter links to plain text"

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.