Tech Note: A PHP Function to Properly Calculate the Length of a Tweet Before Sending It

Learning how to count
LGF • Views: 18,248
Image via Shutterstock

As everyone who uses Twitter knows, there’s a limit of 140 characters per tweet. For Twitter API programmers like me, this means your code has to make sure the tweet you’re about to send is not longer than 140 characters, or Twitter will smack you on the knuckles with a ruler and send back the dreaded error message:

Error: 403 - Status is over 140 characters

So what’s the problem, you ask? Just get the length of the tweet you’re proposing to send and make sure it isn’t over 140 characters. Easy, right?

Well, it used to be this easy, but then Twitter started automatically running all links in tweets through their own custom URL shortener ( — even if they’re already shortened with another service.

(Note: when you look at a tweet on Twitter, you won’t necessarily see the “” URL, either; Twitter automatically expands these links when it displays a tweet. But it’s stored internally as a “” URL.)

This change made correctly calculating the length much more complex; now your code has to scan the tweet text to find URLs, and adjust the overall length to account for what happens when Twitter’s URL shortener does its thing.

If you’re doing this calculating in Javascript, you’re in luck; there’s an official Twitter text processing library for Javascript that includes a method called getTweetLength().

But if you need to calculate the length in a PHP script, you’re not so lucky. There is a PHP version of the twitter-text library, but the latest version doesn’t have a getTweetLength() function, alas.

Which brings us to the point of this post: my version of getTweetLength() for PHP (implemented in our “Now Playing” auto-tweets).

This code uses the PHP twitter-text scripts (linked above), so you’ll need to first upload them to a convenient place in your server’s PHP include path.

A summary of how it works: it’s called with two parameters, the tweet text string, and a true/false flag called $gotImage which indicates whether the tweet will have an image attached. It sets up variables for the lengths of http and https URLs, and the length of an image URL. Then it calls the Twitter_Extractor class (as a singleton) to parse the tweet with a whole bunch of magical regular expressions, and return all the data about it in an associative array called $urlData. (If you run tests/example.php from the PHP twitter-text package, you’ll see the structure of this array.)

Then the code gets the “raw” length of the tweet in the variable $tweetLength (oddly enough), and goes into a loop for each URL found in the tweet, first subtracting the raw length of the URL from $tweetLength, then adding back the length of the URL. It checks to see if the original URL was an http or https link, and adjusts accordingly.

When the loop finishes, it checks to see if the tweet has an image, and adds the length of that URL (which will also end up shortened with In this example, we’re just assuming there’s no image, so we pass FALSE to the function.

Note: Twitter recommends that you use their API to check the default lengths of shortened URLs on a periodic basis, because they might change.

require_once 'twitter-text/Extractor.php';

function getTweetLength($tweet, $gotImage) {
	$tcoLengthHttp = 22;
	$tcoLengthHttps = 23;
	$twitterPicLength = 22;
	$urlData = Twitter_Extractor::create($tweet)->extract();
	$tweetLength = mb_strlen($tweet);
	foreach ($urlData['urls_with_indices'] as $url) {
		$tweetLength -= mb_strlen($url['url']);
		$tweetLength += mb_stristr($url['url'], 'https') === 0
			? $tcoLengthHttps
			: $tcoLengthHttp;
	if ($gotImage) $tweetLength += $twitterPicLength;
	return $tweetLength;

$tweet = '#NowPlaying Fountains of Wayne > Fountains of Wayne > Leave the Biker';
if (getTweetLength($tweet, FALSE) > 140) {
	echo 'Error! The tweet is longer than 140 characters.';
} else {

^ back to top ^


Turn off all ads for a full year by subscribing!
For about 33 cents a day (per month) or 22 cents a day (per year), our subscription option turns off all advertisements at LGF!

► LGF Headlines

  • Loading...

► Tweeted Articles

  • Loading...

► Tweeted Pages

  • Loading...

► Top 10 Comments

  • Loading...

► Bottom Comments

  • Loading...

► Recent Comments

  • Loading...

► Tools/Info

► Tag Cloud

► Contact

You must have Javascript enabled to use the contact form.
Your email:



Messages may be published unless you request otherwise.
Tech Note:
Using the Contact Form
LGF Pages

This button leads to the main index of LGF Pages, our user-submitted articles. You can post your own LGF Pages simply by registering a free account with us.

Create a Page

This is the LGF Pages posting bookmarklet. To use it, drag this button to your browser's bookmark bar, and title it 'LGF Pages' (or whatever you like). Then browse to a site you want to post, select some text on the page to use for a quote, click the bookmarklet, and the Pages posting window will appear with the title, text, and any embedded video or audio files already filled in, ready to go.

Last updated: 2014-03-07 2:19 pm PST

LGF User's Guide
Recent Pages
Skip Intro
Tea Party Candidate Curt Clawson Wins Republican Primary to Replace Former Rep. Trey Radel
Curt Clawson, a businessman who was little known months ago in Southwest Florida, won a contentious GOP primary Tuesday to fill the U.S. House seat left open by the scandalous downfall of Trey Radel. Clawson pitched himself as an ...

6 hours, 31 minutes ago
Views: 76 • Comments: 0
Tweets: 0 • Rating: 0
2014 Rip Curl Pro Bells Beach - ASP - Finals Day!
More: 2014 Rip Curl Pro Bells Beach - ASP The women's final is in the water now and the men's quarterfinals begin after a champion is crowned. Bells beach is delivering the goods today with clean conditions for the ...

7 hours, 4 minutes ago
Views: 47 • Comments: 0
Tweets: 1 • Rating: 0
Randall Gross
Kansas Man Seeks to Hide ‘Murder’ Tattoo Before His Murder Trial
A Kansas man charged with first-degree murder is afraid the tattooed mirror-image letters spelling out the word "murder" across his neck might prejudice a jury, so he is asking for a professional tattoo artist to remove or cover it ...

7 hours, 32 minutes ago
Views: 87 • Comments: 0
Tweets: 0 • Rating: 0
Political Atheist
NYT Story-American Middle Class Is No Longer the World’s Richest
After-tax middle-class incomes in Canada -- substantially behind in 2000 -- now appear to be higher than in the United States. The poor in much of Europe earn more than poor Americans. The income data were compiled by LIS, ...

11 hours, 40 minutes ago
Views: 107 • Comments: 0
Tweets: 0 • Rating: 2
Russ Campbell’s Blog: David Cameron Says Britain Is a Christian Country—He Is Correct
Much is be&shy;ing writ&shy;ten about the United King&shy;dom's Prime Min&shy;is&shy;ter David Cameron's re&shy;cent as&shy;ser&shy;tion that Britain is "a Chris&shy;t&shy;ian coun&shy;try." While some re&shy;li&shy;gious groups like the Hindu Coun&shy;cil UK and the Mus&shy;lim Coun&shy;cil of Britain seem com&shy;fort&shy;able with the ...

16 hours, 29 minutes ago
Views: 132 • Comments: 3
Tweets: 0 • Rating: 1
8 Most Absurd Lessons Americans Teach Kids About Sex
Despite the fact that 95 percent of Americans have premarital sex, and that this has been true for decades, abstinence-only education continues to be taught in classrooms across the U.S. Abstinence programs have received $1.75 billion in federal funds ...

1 day, 6 hours ago
Views: 287 • Comments: 0
Tweets: 0 • Rating: 3
Debate Discrimination - Houston Chronicle
We're glad to see Mayor Annise Parker finally stand up and propose a human rights commission that will provide local due process for victims of public discrimination. Parker told the Chronicle editorial board that she plans to release a ...

3 days, 10 hours ago
Views: 212 • Comments: 0
Tweets: 0 • Rating: 0
Idle Drifter
Calgary stabbings: How knife crime in Canada can cause ‘moral panic’
What Calgary police chief Rick Hanson called the "worst mass murder" in the city's history didn't end at the barrel of a gun. Instead, the 22-year-old suspect identified on Tuesday as Matthew de Grood is accused of entering the kitchen ...

6 days ago
Views: 357 • Comments: 6
Tweets: 0 • Rating: 0
New York Electoral College: State Joins National Popular Vote Interstate Compact.
Ben Mathis-Lilley, Slate: New York Electoral College: State Joins National Popular Vote Interstate Compact. Instead of pushing for a Constitutional amendment, which would have to be ratified in 38 states, advocates ask individual state legislatures to pass an agreement: that ...

6 days, 7 hours ago
Views: 347 • Comments: 8
Tweets: 0 • Rating: 2
Drug Companies Want Your Money
Two thematically-related stories on the BBC at the moment: UK drug company Glaxo 'paid bribes to Polish doctors' UK drug company GlaxoSmithKline is facing a criminal investigation in Poland for allegedly bribing doctors, BBC Panorama has discovered. Tamiflu: Millions wasted ...

1 week ago
Views: 349 • Comments: 0
Tweets: 8 • Rating: 0
 Frank says:

Playing guitar with this band is like trying to grow watermelon in Easter hay.