Because of the new Twitter API, I am using PHP to display 1 latest tweet on my webpage using PHP.
At the moment I have got it working so that the tweet is just outputted as a simple text string. My question is how do I control the HTML outputted? I want to be able to display the links as links if a hashtag or web address is stated within the tweet. How do I do this?
Here's my code so far that outputs the string as a tweet in my page:
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($tweets[0]['text']);
}
A simple regular expression will work in most cases. But Twitter entities solve the parsing problem for you, plus give you more information about links, usernames, etc.
See The full documentation here: https://dev.twitter.com/overview/api/entities-in-twitter-objects
To format the text, get a list of all replacements you need to make, then do the replacements in reverse order (so the offsets stay correct after the text is expanded).
Here is some example code for replacing links, hashtags and attags with links in php
This gives the output
So you could change your code to
I'm sure the regex's could be improved though.
Or even better you can then split it out into it's own function.