0

I need to find out if a message fits into the 140 character limit of Twitter. This is what I have so far:

$tweetLength = strlen(utf8_decode($_POST["message"]));
if($tweetLength<141){
sendMessage();
}

Links get converted by Twitter into a t.co short URL. How to check how many links are in the message and replace their length with the short-link counterparts?

  • a http:// link counts for 22 characters
  • a https:// link counts for 23 characters

Links can start with http://www, https://www or www.

Tom
  • 5,588
  • 20
  • 77
  • 129

3 Answers3

1

You can do it like this:

preg_match_all('/http:.*?com/', $message, $matches);

$message_length = strlen($message);

foreach ($matches as $match) {

    $message_length .= -strlen($match);
    $message_length .= 22;

}

You can handle the https case from here :)

nkconnor
  • 672
  • 3
  • 18
  • Just want to add according to [twitter docs](https://dev.twitter.com/docs/tco-link-wrapper/faq#How_long_are_t.co_links): `If you are not using the opt-in features, only links shorter in length than a t.co URL will be wrapped by t.co.` – dcclassics Jun 04 '14 at 14:19
1

The easy way would be to match all URLS in the tweet using a regular expression, and replace (preg_replace) it with a (dummy) 22 or 23 chars long string. Then you can get the character count.

In order to parse URLs the same way Twitter does, you can dig into the Twitter Text for PHP lib to see how it's really done.

Note that strlen won't work in many cases, since it will count special characters (accentued and others) multiple times because those are multi-byte chars. You need to use mb_strlen (the mb_ stands for *multi-byte) to count that properly.

The developper guide gives detailed insight on how twitter counts chars under the hood:

Tweet length is measured by the number of codepoints in the NFC normalized version of the text.

It even references PHP's Normalizer class to do that.

svvac
  • 5,814
  • 3
  • 17
  • 22
  • Also, have a look at [this post](http://blog.pay4tweet.com/2012/04/27/twitter-lifts-140-character-limit/) that shows how to do exactly that (but in JavaScript) – svvac Jun 04 '14 at 14:19
0

I would use :

$length= strlen(
    preg_replace(
        '/(?:http(s)?:\/\/|www\.)\S+/', 
        'xxxxxxxxxxxxxxxxxxxxxx$1', 
        $message
    )
);

This will replace :

  • http://www.stackoverflow.com into xxxxxxxxxxxxxxxxxxxxxx
  • https://www.stackoverflow.com into xxxxxxxxxxxxxxxxxxxxxxs
  • www.stackoverflow.com into xxxxxxxxxxxxxxxxxxxxxx
  • http://g.co into xxxxxxxxxxxxxxxxxxxxxx
  • https://g.co into xxxxxxxxxxxxxxxxxxxxxxs
  • www.g.co into xxxxxxxxxxxxxxxxxxxxxx

Then, your string has the final length, and you can easily check it :

if ($length <= 140) {
    sendMessage();
}
zessx
  • 68,042
  • 28
  • 135
  • 158