diff --git a/twitter.lib.php b/twitter.lib.php
index 8e2eb60..cda8301 100644
--- a/twitter.lib.php
+++ b/twitter.lib.php
@@ -229,10 +229,30 @@ class Twitter {
 
     switch ($format) {
       case 'json':
-        // http://drupal.org/node/985544 - json_decode large integer issue
-        $length = strlen(PHP_INT_MAX);
-        $response = preg_replace('/"(id|in_reply_to_status_id)":(\d{' . $length . ',})/', '"\1":"\2"', $response);
-        return json_decode($response, TRUE);
+        // 64bit version of PHP can handle big integers natively.
+        if (PHP_INT_SIZE >= 8) {
+          $response_decoded = json_decode($response, TRUE);
+        }
+        // Have a version of PHP that can store big integers as
+        // a string to avoid float conversion.
+        elseif (defined('JSON_BIGINT_AS_STRING')) {
+          $response_decoded = json_decode($response, TRUE, 512, JSON_BIGINT_AS_STRING);
+        }
+        // Need to deal with large integers, because PHP will convert them
+        // to floats if they are greater than PHP_INT_MAX.
+        else {
+          $response_decoded = json_decode($response, TRUE);
+          if ($response_decoded['id_str']) {
+            // Single object back as JSON.
+            Twitter::json_bigint_kludge($response_decoded);
+          } else {
+            // Array of objects as JSON.
+            foreach ($response_decoded as &$item) {
+              Twitter::json_bigint_kludge($item);
+            }
+           }
+         }
+         return $response_decoded;
     }
   }
 
@@ -246,6 +266,23 @@ class Twitter {
     }
     return $url;
   }
+
+  /**
+   * Attempt to fetch VALUE_str when we are on a system which
+   * is likely to experience #985544: truncated large integers from JSON.
+   */
+  protected function json_bigint_kludge(&$arr) {
+    $status_keys = array('id', 'in_reply_to_status_id', 'in_reply_to_user_id');
+    foreach ($status_keys as $status_key) {
+      $str_key = $status_key . '_str';
+      if (isset($arr[$str_key]) && isset($arr[$status_key])) {
+        $arr[$status_key] = $arr[$str_key];
+      }
+    }
+    if (isset($arr['user']['id_str']) && isset($arr['user']['id'])) {
+      $arr['user']['id'] = $arr['user']['id_str'];
+    }
+  }
 }
 
 /**
