I am trying to run a regex on a JSON string to verify data is as expected before continuing with my script.
Here is an example of the JSON to run the regex on:
[{"id":"01001001","b":"1","c":"1","v":"1","t":"Some \"Text\""},{"id":"01001002","b":"1","c":"1","v":"2","t":"More Text"},{"id":"01001003","b":"1","c":"1","v":"3","t":"And Even More"}]
I have tested the following regex as working at phpliveregex.com:
\[(\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})(,\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})*\]
Here is how I put it together in PHP:
$sv = '01001001';
$ev = '01001003';
$url = 'http://api.amasterdesigns.com/?sv='.$sv.'&ev='.$ev;
$JSON = file_get_contents($url);
//return JSON only if properly formatted
if(preg_match('/\[(\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})(,\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})*\]/',$JSON)){
return json_decode($JSON);
} else {
return;
}
The problem I am receiving is when I run this page I receive this error
Warning: preg_match(): Compilation failed: missing terminating ] for character class at offset 202 in path_to_file/my-file.php on line 1422
Line 1422 is line 6 of the above code snippet. I believe this is pointing to [^"\\]
near the end of my regex, but I do have a terminating ]
following an escaped \
.
You can see the errors using PHP sandbox