I try build a php regex that validate this type of input string:
{name:'something name here',type:'',id:''},{name:'other name',type:'small',id:34},{name:'orange',type:'weight',id:28}
etc…
So, it is a list of json that each contain 3 field: name,type,id.Field name is always present, instead type and id can be together empty string ( ” ). Then I can explode it by comma if it has valid format and obtain a array of json string.
How can I do?
UPDATE
it isn’t a valid json as you can say but I have a input field where user put tags, and I want track a name, type and id of that tags.
example:
tag1 (has name,type,id), tags2 (has only name), tags3(has name, type,id).
So, I think that I can post a string in that format:
{'name':'test','type':'first','id':3},{'name':'other','type':'second','id':45}, etc
But I must validate this string with a regex. I can do
$data = explode(',',$list);
and then I do:
foreach($data as $d){
$tmp = json_decode($d);
if($tmp == false) echo 'error invalid data';
}
As Gubo pointed out: this is not a valid JSON encoded string. If the actual data you want to process in your script ís valid however, you’re barking up the wrong tree looking for a regular expression… PHP has tons of functions that will parse JSON strings much faster than a regular expression.
Where
$string2is the data in valid JSON formar. If your data is a valid JSON string, the following code will suffice:If, however you’re dealing with invalid JSON strings, things get a bit more complicated… First off: if you’re lacking your object properties (or array keys as they will become in PHP) are quoted, a quick fix would be this:
If you really want to parse them seperatly:
But I can’t see why you would want to do that. The biggest issue here is the absence of quotes on the property strings (or keys). I have put together a regex (untested) that could quote those strings:
Keep in mind, the last regex is untested, so it might not perform as you expect it to… but it should help you on your way… for the last example, the same rules apply for all the other examples I gave: if the quotes and brackets are there, just use
json_decode, if the brackets are missing, add them, too…It’s getting rather late here, so I’m off to bed now… I hope this answer isn’t packed with typo’s and sentences that nobody can understand. If it is, I do apologize.