$re = '/(?P<hit_count>"hit_count"\s*:\s*"\{\\\\\"(?P<group_by>[^\\\\\"]+)\\\\\":\{(?:\\\\\"([^\\\\\"]+)\\\\\":([0-9]+))?(?:,\\\\\"([^\\\\\"]+)\\\\\":([0-9]+))?(?:,\\\\\"([^\\\\\"]+)\\\\\":([0-9]+))?(?:,\\\\\"([^\\\\\"]+)\\\\\":([0-9]+))?(?:,\\\\\"([^\\\\\"]+)\\\\\":([0-9]+))?(?:,\\\\\"([^\\\\\"]+)\\\\\":([0-9]+))?\}\}")/m';
$str = '{"integration_text":"A Coralogix alert has been triggered!","alert_url":"https://Medigate.coralogix.com/#/insights?id=00270770-5eed-11eb-91d9-fd643179e246","alert_subsystem":"Multiple Subsystems","alert_severity":"INFO","alert_id":"3f99f720-5afe-11eb-94ee-09d1be14b22b","alert_application":"Multiple Applications","hit_count":"{\\"host.hostname\\":{\\"ksbl-liestal-collection-laufen\\":27,\\"quiron-hev-collection\\":27,\\"klinikumdo-main-collection\\":16,\\"zgks-zug-collection\\":1}}","alert_name":"Medparser KA"}
{"integration_text":"A Coralogix alert has been triggered!","alert_url":"https://Medigate.coralogix.com/#/insights?id=cc3da9c0-5eef-11eb-8c43-5b48837995a8","alert_subsystem":"Multiple Subsystems","alert_severity":"INFO","alert_id":"7097bde0-5b0c-11eb-8a52-29a11019991e","alert_application":"Multiple Applications","hit_count":"{\\"host.hostname\\":{\\"chtourcoing-main-analysis\\":6,\\"mannheimu-main-analysis\\":6,\\"clalit-soroka-analysis\\":5,\\"maastrichtu-main-analysis\\":5,\\"ntu-taipei-analysis\\":5}}","alert_name":"Medalert Activity KA"}
';
$subst = "$1,\"hit_count_object\":{\"group_by\":\"$2\",\"hits\":[{\"key\":\"$3\",\"count\":$4},{\"key\":\"$5\",\"count\":$6},{\"key\":\"$7\",\"count\":$8},{\"key\":\"$9\",\"count\":$10},{\"key\":\"$11\",\"count\":$12}]}";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php