PHP中的字符串替换需要帮助[重复]

ohtdti5x  于 2023-06-04  发布在  PHP
关注(0)|答案(1)|浏览(125)

此问题已在此处有答案

How to edit specific JSON key values using PHP(3个答案)
昨天关门了。
我有一个这样的字符串:

$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}'

我想把字符串分成两部分-[{"action": "verify_with_source",..."type": "license"}]{"category":"NT","cov":"LMV","issue_date":"2021-03-30"}],...,"t_validity_to":null"}
“我和他分手了。

$raw = str_replace(['[', ']'], '', $raw);

我试过了-

$str = preg_replace('^/} {/', '}{', $raw);

和/或

$str = preg_replace('^/}\s{/', '}{', $raw);

和/或

$str = str_replace('} {', '{}', $raw);

然后我打算用语句将字符串$str拆分为2个字符串的数组-

$arr = explode('}{', $str);

字符串没有被拆分,上面的语句返回数组第一个元素中的整个字符串。
我的剧本有什么问题?

fhity93d

fhity93d1#

我会建议让它更容易一点,而不是更换所有的支架。
explode可以为你处理这个问题,并在你想要的地方分割字符串。因此,只需在许可证结束和对象开始的位置] {处将其拆分,然后将缺少的大括号添加到该字符串中。

<?php

$str = "<your long string>"

$jsonStrings = explode('] {', $str, 1);

$jsonStrings[0] .= ']';
$jsonStrings[1] = '{' . $jsonStrings[1];

注意没有错误处理。如果字符串中没有] {字符,explode将不会创建一个包含两个字符串的数组,并且其余代码将失败。

相关问题