//平衡组正则提取字符串中的 json 部分内容
public static function getJsonFromStr($str) {
if(!preg_match("/{{([^\}]+)}}/", $str) && !preg_match("/{([^\}]+)}/", $str) ) return $str;
$tmpSplitTag = 'lrSplit';
$N =0;
$newStr = $str;
$zhushiLeft = '\\{';
$zhushiLeft1 = 'lrHkhZs1';
$zhushiRight = '\\}';
$zhushiRight1 = 'lrHkhZs2';
$newStr = str_replace($zhushiLeft, $zhushiLeft1, $newStr);
$newStr = str_replace($zhushiRight, $zhushiRight1, $newStr);
$newStr = preg_replace_callback("/{|}/u", function ($match) use($tmpSplitTag, &$N) {
// print_r($match[0] .'
');
if($match[0]==="{") {
return "[" . $tmpSplitTag . (++$N) . "]";
}
if($match[0]==="}"){
return "[/". $tmpSplitTag .($N--) ."]";
}
} , $newStr);
// print_r($newStr);
// exit;
//将首节点复原成 { }
$newStr = preg_replace("/\[". $tmpSplitTag ."1\]/u", '{', $newStr);
$newStr = preg_replace("/\[\/". $tmpSplitTag ."1\]/u", '}', $newStr);
//提取首级节点
$findFirstTagStr = function($restStr)use($zhushiLeft,$zhushiLeft1,$zhushiRight,$zhushiRight1) {
$firstTagArray = [];
preg_match("/{[^\}]+}/", $restStr, $findTag);
$findStr = $findTag[0];
$jsonStr = $findStr;
// var_dump($findTag);
if($findTag) {
$findIndex = strpos($restStr, $jsonStr);
// var_dump($findIndex);
$jsonStr = str_replace($zhushiLeft1, $zhushiLeft, $jsonStr);
$jsonStr = str_replace($zhushiRight1, $zhushiRight, $jsonStr);
if($findIndex===0) {
$firstTagArray[] = '';
$firstTagArray[] = $jsonStr;
} else {
$firstTagArray[] = substr($restStr, 0, $findIndex);
$firstTagArray[] = $jsonStr;
}
$rightStr = mb_substr($restStr, $findIndex + mb_strlen($findStr));
if(!$rightStr) {
$rightStr = '';
}
$firstTagArray[] = $rightStr;
} else {
$firstTagArray[] = $restStr;
}
return $firstTagArray;
};
$firstTagArray = $findFirstTagStr($newStr);
//复原
foreach($firstTagArray as $n_=> $str_) {
$newStr_ = $str_;
$newStr_ = preg_replace("/\[". $tmpSplitTag ."\d+\]/i", '{', $newStr_);
$newStr_ = preg_replace("/\[\/". $tmpSplitTag ."\d+\]/i", '}', $newStr_);
if($newStr_ !== $str_) {
$firstTagArray[$n_] = $newStr_;
}
}
//剩下的字符串继续查找
$endStr = $firstTagArray[2];
$endStrArray = self::getJsonFromStr($endStr);
if($endStrArray) {
unset($firstTagArray[2]);
$firstTagArray = array_merge($firstTagArray, $endStrArray);
}
foreach ($firstTagArray as $n_=>$v_) {
if(!$v_) unset($firstTagArray[$n_]);
}
return $firstTagArray;
}
public function test() {
$str = 'asddsadas{"UCName":"aaaa","firmwareModelData":"{\"type\":\"uimg\",\"value\":\"a\{12\{\}\{\{\"asdasd\"}}adsads{"UCName":"aaaa","firmwareModelData":"{\"type\":\"uimg\",\"value\":\"a\{12\{\}\{\{\"asdasd\"}}';
$jsonData = Str::getJsonFromStr($str);
$list_ = [];
if(is_array($jsonData)) {
foreach ($jsonData as $v_) {
if(preg_match("/^\{.+\}$/", $v_)) {
$list_[] = '