I am just working on a related problem (find the missing square bracket of the array in the JSON object). Therefore, I hope to help.
$pos=0; $braceCount=0; while( preg_match('~\{|\}~S', $source, $out, PREG_OFFSET_CAPTURE, $pos) ){ if($out[0][0] === '{'){ $braceCount++; if( $braceCount === 1 )$startPos=$out[0][1]; } elseif( $out[0][0] === '}' ){ $braceCount--; if( $braceCount === 0 ){ //echo 'Up to that position:'.$out[0][1].' every thing seems to be ok?<br>'; echo substr($source,$startPos,($out[0][1]+1-$startPos)).'<br>'; } elseif( $braceCount < 0 ){ echo 'To many closing brace right before '.($out[0][1]+1).'<br>'; exit; } } $pos = $out[0][1]+1; } if( $braceCount > 0 ) echo 'Closing brace is missing somewhere.';
This drives the source away until a skip match and an error for curly braces appear.
source share