Created
September 18, 2025 06:42
-
-
Save juanparati/819122bbb1aadf5d12a01c5646521d49 to your computer and use it in GitHub Desktop.
Extract JSON objects from a a string faster than use regular expressions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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