title: Parsing serialized PHP data with BNF using Instaparse
body: <p>I have a value serialized by PHP that I need to decode in Clojure.  I'm using this <a href="https://gist.github.com/terjesb/5910504" rel="nofollow">library</a> to deserialize it; it uses <a href="https://github.com/Engelberg/instaparse" rel="nofollow">Instaparse</a> which utilizes EBNF/ABNF notation to define the grammar.  For reference, here's the full definition:</p>
  
  <pre><code>&lt;S&gt; = expr
  &lt;expr&gt; = (string | integer | double | boolean | null | array)+
  &lt;digit&gt; = #'[0-9]'
  &lt;number&gt; = negative* (decimal-num | integer-num)
  &lt;negative&gt; = '-'
  &lt;integer-num&gt; = digit+
  &lt;decimal-num&gt; = integer-num '.' integer-num
  &lt;zero-or-one&gt; = '0'|'1'
  size = digit+
  key = (string | integer)
  &lt;val&gt; = expr
  array = &lt;'a:'&gt; &lt;size&gt; &lt;':{'&gt; (key val)+ &lt;'}'&gt; &lt;';'&gt;?
  boolean = &lt;'b:'&gt; zero-or-one &lt;';'&gt;
  null = &lt;'N;'&gt;
  integer = &lt;'i:'&gt; number &lt;';'&gt;
  double = &lt;'d:'&gt; number &lt;';'&gt;
  string = &lt;'s:'&gt; &lt;size&gt; &lt;':\\\"'&gt; #'([^\"]|\\.)*' &lt;'\\\";'&gt;
  </code></pre>
  
  <p>I've found a bug in this library - it can't handle serialized strings that contain the <code>"</code> character.</p>
  
  <pre><code>php &gt; echo serialize('{"key":"value"}');
  s:15:"{"key":"value"}";
  </code></pre>
  
  <p>Deserialized using the library, it blows up when it finds that second <code>"</code>:</p>
  
  <pre><code>&gt; (deserialize-php "s:15:\"{\"key\":\"value\"}\";")
  [:index 7]
  </code></pre>
  
  <p>The problem exists on this line of the grammar definition:</p>
  
  <pre><code>string = &lt;'s:'&gt; &lt;size&gt; &lt;':\\\"'&gt; #'([^\"]|\\.)*' &lt;'\\\";'&gt;
  </code></pre>
  
  <p>You'll notice that the string definition excludes the <code>"</code> character.  That's not correct though, I could have any character in that string; the size is what matters.  I'm not a BNF expert, so I'm trying to figure out what my options here are.</p>
  
  <p>Is it possible to use the size as the correct number of characters to grab?  If that's not possible, does someone see a way I can tweak the grammar definition to enable correct parsing?</p>