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

Learning how to count
LGF • Views: 18,208
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
Randall Gross
Hands on With Facebook’s Nearby Friends
There's a lot that Facebook allows you to share with your friends. On Thursday, the company added "exact location" to that list. Facebook's new Nearby Friends feature enables you to flip a switch to start broadcasting your location with friends in the area. If you see someone nearby with whom you want to meet up, you can tap a button, and send them ...

5 hours, 20 minutes ago
Views: 66 • Comments: 0
Tweets: 0 • Rating: 0
A 12-Year-Old’s Trek of Despair Ends in a Noose at the Border
Noemi &Aacute;lvarez Quillay took the first steps of the 6,500-mile journey to New York City from the southern highlands of Ecuador on Tuesday, Feb. 4, after darkness fell. A bashful, studious girl, Noemi walked 10 minutes across dirt roads that cut through corn and potato fields, reaching the highway to Quito. She carried a small suitcase. Her grandfather Cipriano Quillay flagged down a ...

5 hours, 22 minutes ago
Views: 173 • Comments: 0
Tweets: 0 • Rating: 1
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 formal version of her proposal within the next few weeks, but sometimes the process is just as important as the result. As the energy ...

23 hours, 2 minutes ago
Views: 112 • Comments: 0
Tweets: 0 • Rating: 0
Russ Campbell’s Blog: Bill C-23, Fair Elections Act Seems Now on Solid Ground
Now that a Sen&shy;ate com&shy;mit&shy;tee has rec&shy;om&shy;mended nine changes to Bill C-23, Fair Elec&shy;tions Act, the leg&shy;is&shy;la&shy;tion seems pretty solid. And, since Pierre Poilievre has, ap&shy;par&shy;ently, in&shy;di&shy;cated pri&shy;vately that he's open to changes, an amended ver&shy;sion of the bill will likely be&shy;come law by this sum&shy;mer. We would prob&shy;a&shy;bly have got&shy;ten to this point ear&shy;lier had not the min&shy;is&shy;ter re&shy;spon&shy;si&shy;ble for the bill ...

1 day, 1 hour ago
Views: 91 • Comments: 2
Tweets: 0 • Rating: 0
Live now - 2014 Rip Curl Pro Bells Beach - ASP World Tour
More: 2014 Rip Curl Pro Bells Beach - ASP Iconic Bells Beach in Victoria, Australia once again hosts the world's best surfers for the 41st running of the Bells Beach Contest. New feature in this broadcast: drone cam!

1 day, 21 hours ago
Views: 192 • Comments: 0
Tweets: 3 • Rating: 0
Skip Intro
Why the Temperature of the Yellow Sea Is a Big Deal, and Other Questions About the South Korean Ferry Disaster
The boat ran into trouble several dozen miles from Jindo, an island that sticks out of South Korea's southwestern corner like a little toe. Jindo is surrounded by a group of even smaller islands that are slightly farther afield from the mainland. The ferry was curving around those small islands at the time it issued a distress call. What caused the disaster? We ...

2 days, 2 hours ago
Views: 365 • Comments: 3
Tweets: 25 • Rating: 1
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 at a house party, taking "a large knife" and using it to fatally stab four men and one woman, all of whom were students ...

3 days, 13 hours ago
Views: 257 • Comments: 5
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 they'll pledge all their presidential electors to the winner of the national popular vote as soon as enough other states pass the law to ...

3 days, 19 hours ago
Views: 266 • Comments: 7
Tweets: 0 • Rating: 2
Political Atheist
The Insane History of Rockets at Jet Propulsion Laboratories
The Rocket Boys In the late 1930s, a group of Caltech graduate students were booted off campus after blowing up (part of!) their building during a rocket test gone awry. Unwilling to give up on the joy of semi-controlled explosions, the students and a few of their friends headed into the San Gabriel Mountains. They picked a deserted gully -- Arroyo Seco -- ...

4 days, 16 hours ago
Views: 289 • Comments: 0
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 on flu drug, claims major report Hundreds of millions of pounds may have been wasted on a drug for flu that works no better ...

4 days, 22 hours ago
Views: 285 • Comments: 0
Tweets: 8 • Rating: 0
 Frank says:

Ooooh the way you love me baby,
I get so hard now I could die.
Ooooh the way you squeeze me lady
red balloons just pop behind my eyes -- Magic Fingers, 200 Motels