I have a string like this:
$str = '[{"action": "verify_with_source","created_at": "2023-05-30T01:39:54+05:30","status": "in_progress","type": "license"}] {"address":null,"badge_details":null,"card_serial_no":null,"city":null,"cov_details":[{"category":"NT","cov":"MCWG","issue_date":"2021-03-30"},{"category":"NT","cov":"LMV","issue_date":"2021-03-30"}],"date_of_issue":"2021-03-30","date_of_last_transaction":"2021-03-30","dl_status":"Active","dob":"1996-10-09","face_image":null,"gender":null,"hazardous_valid_till":null,"hill_valid_till":null,"id_number":"DL1234567890","issuing_rto_name":"MY CITY","last_transacted_at":"MY CITY","name":"MY NAME","nt_validity_from":"2021-03-30","nt_validity_to":"2036-10-08","relatives_name":null,"source":"SOURCE","status":"id_found","t_validity_from":null,"t_validity_to":null}'
What I want to split the string in 2 parts - [{"action": "verify_with_source",..."type": "license"}]
and {"category":"NT","cov":"LMV","issue_date":"2021-03-30"}],...,"t_validity_to":null"}
.
I removed [ and ] with -
$raw = str_replace(['[', ']'], '', $raw);
Then, I have tried-
$str = preg_replace('^/} {/', '}{', $raw);
and
$str = preg_replace('^/}\s{/', '}{', $raw);
and
$str = str_replace('} {', '{}', $raw);
Then I intend to split string $str
into array of 2 strings with statement -
$arr = explode('}{', $str);
The string is not being splitted and above statement returns whole string in first element of array.
What is wrong with my script?
I would suggest to make it a bit easier instead of replacing all the braces.
explode can handle that for you and split the string at a place you want. So just split it at the position ] {
where the license ends and the objects starts and add the missing braces afterwards to that strings.
<?php
$str = "<your long string>"
$jsonStrings = explode('] {', $str, 1);
$jsonStrings[0] .= ']';
$jsonStrings[1] = '{' . $jsonStrings[1];
be aware of there is no error handling. if there is no ] {
chars in your string, explode will not create an array with two strings and the rest of the code is failing.