title: PHP/Regex: Parse JSON in string
body: <p>I'm trying to find simple key-value-pairs in strings, given as JSON-objects, while using preg_replace_callback().</p>
  <p>Unfortunately, the values given can be of type string, number, boolean, null, array - and worst of all - objects. My own attempts solving this problem resulted in either an incomplete selection or over-selecting multiple JSON occurances as one.</p>
  <p><strong>Here the things i tried:</strong></p>
  <pre><code>String:
  text text {&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}} text
  
  Regex:
  \{&quot;(.+?)&quot;\:(.+?)\}
  
  Match:
  {&quot;key&quot;:&quot;value&quot;
  </code></pre>
  <p>Above: This ignores the inner }-bracket</p>
  <pre><code>String:
  text text {&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}} text
  
  Regex:
  \{&quot;(.+?)&quot;\:(.+)\}
  
  Match:
  {&quot;key&quot;:&quot;value&quot;}
  </code></pre>
  <p>Above: This would (theoretically) work, but when having multiple JSON occurances, i get:</p>
  <pre><code>{&quot;key&quot;:&quot;value&quot;}} {&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}
  </code></pre>
  <p>Next attempt:</p>
  <pre><code>String:
  text text {&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}} {&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}} text
  
  Regex:
  \{&quot;(.+?)&quot;\:(?:(\{(?:.+?)\})|(?:&quot;)?(.+?)(?:&quot;)?)\}
  
  Match:
  {&quot;key&quot;:&quot;value&quot;}
  </code></pre>
  <p>Above: Again, that would theoreticcally work. But when taking, for example, the following string:</p>
  <pre><code>text text {&quot;key&quot;:{&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}}} text
  </code></pre>
  <p>The result is...</p>
  <pre><code>{&quot;key&quot;:{&quot;key&quot;:&quot;value&quot;}
  </code></pre>
  <p>Missing one bracket</p>