Skip to content

Instantly share code, notes, and snippets.

@juanparati
Created September 18, 2025 06:42
Show Gist options
  • Select an option

  • Save juanparati/819122bbb1aadf5d12a01c5646521d49 to your computer and use it in GitHub Desktop.

Select an option

Save juanparati/819122bbb1aadf5d12a01c5646521d49 to your computer and use it in GitHub Desktop.
Extract JSON objects from a a string faster than use regular expressions.
/**
* Extract all JSON objects (doens't work with JSON arrays) from a string.
*
* This method is the alternative to '/\{(?:[^{}]|(?R))*}/m' regular expression but faster
* according to https://3v4l.org/4WtGX VS https://3v4l.org/N9oRi
*
*/
function jsonExtract(string $str) : array
{
$numBrackets = $initStr = $foundAt = -1;
$strings = [];
foreach (str_split($str) as $k => $chr) {
switch ($chr) {
case '{':
$numBrackets++;
if ($initStr === -1) {
$initStr = $k;
}
break;
case '}':
if ($initStr >= 0) {
$numBrackets--;
if ($numBrackets === -1 && $foundAt > -1) {
$strings[] = substr($str, $foundAt, $k - $foundAt + 1);
$numBrackets = $initStr = $foundAt = -1;
}
}
break;
case '"':
if ($numBrackets > -1 && $foundAt === -1) {
$foundAt = $initStr;
}
break;
}
}
return $strings;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment