PHP Twitter Replace Link and Hashtag with Real Link

Turn a twitter hash tag into a link and links to clickable links

$str = preg_replace('/\#([a-z0-9]+)/i', '<a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $str);

EDIT

In terms of the two different patterns, just do:

$str = preg_replace(array($url_pattern, $hash_pattern), array($url_replacement, $hash_replacement), $str);

PHP: How to use the Twitter API's data to convert URLs, mentions, and hastags in tweets to links?

All you have to do to use the indices twitter provides straight up with a simple replace is collect the replacements you want to make and then sort them backwards. You can probably find a more clever way to build $entities, I wanted them optional anyway, so I KISS as far as that went.

Either way, my point here was just to show that you don't need to explode the string and character count and whatnot. Regardless of how you do it, all you need to to is start at the end and work to the beginning of the string, and the index twitter has is still valid.

<?php 

function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true)
{
$return = $tweet->text;

$entities = array();

if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/".$e->screen_name."' target='_blank'>@".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}

usort($entities, function($a,$b){return($b["start"]-$a["start"]);});

foreach($entities as $item)
{
$return = substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}

return($return);
}

?>

Using PHP and the new Twitter API

Here is some example code for replacing links, hashtags and attags with links in php

$tweet = "@george check out http://www.google.co.uk #google";

//Convert urls to <a> links
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);

//Convert hashtags to twitter searches in <a> links
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);

//Convert attags to twitter profiles in <a> links
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);

echo $tweet;

This gives the output

<a href="http://www.twitter.com/george">@george</a> check out <a target="_blank" href="http://www.google.co.uk">http://www.google.co.uk</a> <a target="_new" href="http://twitter.com/search?q=google">#google</a>

So you could change your code to

function get_tweet() {

require 'tmhOAuth.php';
require 'tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'secret',
'consumer_secret' => 'secret',
'user_token' => 'secret',
'user_secret' => 'secret',
'curl_ssl_verifypeer' => false
));

$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'evanrichards',
'count' => '1'));

$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);

$tweet = $tweets[0]['text'];
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
echo($tweet);

}

I'm sure the regex's could be improved though.

Or even better you can then split it out into it's own function.

function linkify_tweet($tweet) {

$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);

return $tweet;

}

function get_tweet() {

require 'tmhOAuth.php';
require 'tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'secret',
'consumer_secret' => 'secret',
'user_token' => 'secret',
'user_secret' => 'secret',
'curl_ssl_verifypeer' => false
));

$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'evanrichards',
'count' => '1'));

$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);

echo(linkify_tweet($tweets[0]['text']));

}

Instagram replace hashtag with real link

You could go for

function hashtag($str) {
return preg_replace(
array('/#(\w+)/', '/@([\w.]+)/'),
# --^--
array(' <a href="/t/$1" class="hashtag">#$1</a>', ' <a href="/u/$1" class="username">@$1</a>'),
$str);
}

Just put it in a character class, that is.

Parse text for hashtags and replace with links using php

Try using this:

$text = "Vivamus #tristique non elit eu iaculis.";
$text = preg_replace('/(?:^|\s)#(\w+)/', ' <a href="tag/$1">$1</a>', $text);
// $text now: Vivamus <a href="tag/tristique">tristique</a> non elit eu iaculis;

Here it is working: https://3v4l.org/WXqTr (click run).

Regex reference: Space or beginning of string, Non capturing group

Original source: Parsing Twitter with RegExp

How to remove # from Twitter hashtags?

You need to surround the part you want to capture in parentheses:

$tweet = preg_replace('/#([\w-]+)/i', '$1', $tweet);

See it working online: ideone

I also changed the regular expression to be more specific, but for an even better regular expression I refer you to this question and its answers (for .NET but the idea is the same in PHP):

  • Best HashTag Regex

How do I linkify Twitter usernames using PHP preg_replace?

Why is the \ there before _? Does it work if you take out the \? Though that shouldn't have broken the functionality...

It might be helpful to change the \1 to \\1 so that you're sure the backslash is escaped; or better (since PHP 4.0.4) $1. But again, it should have worked as-is, within single quotes.

Also, you can simplify:

$pattern = '/@([a-zA-Z0-9_]+)/';
$replace = '<a href="http://twitter.com/$1">@$1</a>';


Related Topics



Leave a reply



Submit