Search code examples
phpapitwitterlimitcharacter

Calculate final tweet character length in PHP


twitter sets a fixed character length of 20 for all links inside tweets.

So even if a user uses an url shortening service like bit.ly and pastes url shorter than 20 characters all urls will finally be given a length of 20 characters by twitter.

I was wondering how to calculate the final length of a tweet(including one or multiple short urls) so it stays under 140 characters with PHP.


Solution

  • You can replace your links with some generic text via regex and count the whole length with mb_strlen() afterwards. mb_strlen because Twitter counts Multibyte chars as one char.

    $tweet = 'Check this: http://stackoverflow.com/questions/8864767/calculate-final-tweet-character-length-in-php';
    $length = mb_strlen(preg_replace('~https?://([^\s]*)~', 'http://8901234567890', $tweet), 'UTF-8');
    var_dump($length); // int(32);
    

    You will probably have to tune the regex a bit as it may match to much (invalid chars)