The following function is essentially the third in a series that look at creating links from URLs, hashtags, and usernames. Intended for Twitter, the same principle applies across multiple networks. THe function's primary purpose is to support the article "Retrieve Your Twitter Follow Count (and Other Data) in Plain Text With WordPress Shortcode or PHP", published here.
We use and reference this function for both PHP and WordPress applications.
1
<?php
2
/*
3
Linkify Links, Twitter Hashtags, and Twitter Usernames
4
http://www.beliefmedia.com/code/php-snippets/linkify-twitter
5
http://www.beliefmedia.com/twitter-data
6
*/
7
8
function beliefmedia_linkify_twitter($text) {
9
$text = preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Z()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $text);
10
$text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="http://twitter.com/search?q=$1" target="_blank" rel="noopener noreferrer">#$1</a>', $text);
11
$text = preg_replace('#@([\\d\\w]+)#', '<a href="http://twitter.com/$1" target="_blank" rel="noopener noreferrer">$0</a>', $text);
12
return $text;
13
}
It's a very basic function with simple expressions... but it'll suffice for most of the uses we have for it.