Index: gettext.php
===================================================================
--- gettext.php	(revision 5072)
+++ gettext.php	(working copy)
@@ -287,7 +287,39 @@
         $expr = $regs[1];
       else
         $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
-      $this->pluralheader = $expr;
+
+      // sanitize
+      $expr = preg_replace(
+        '@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@',
+        '',
+        $expr
+      );
+
+      // add parens
+      // important since PHP's ternary evaluates from left to right
+      $expr.= ';';
+      $res= '';
+      $p= 0;
+      for ($i= 0; $i < strlen($expr); $i++) {
+        $ch= $expr[$i];
+        switch ($ch) {
+          case '?':
+            $res.= ' ? (';
+            $p++;
+            break;
+          case ':':
+            $res.= ') : (';
+            break;
+          case ';':
+            $res.= str_repeat( ')', $p) . ';';
+            $p= 0;
+            break;
+          default:
+            $res.= $ch;
+        }
+      }
+
+      $this->pluralheader = $res;
     }
     return $this->pluralheader;
   }
