Muhammd Azeem Muhammd Azeem - 7 months ago 39
PHP Question

chop and get values of string based on length PHP

This question might look bit weird boot its keep blowing my mind since yesterday. I am getting a string from TCP/IP Packet which is something like this..


"SiteName":"GPRSSignalStrength":"SelectedNetworkOperators":"GPRSReportingTimeOut":"SensorReportCount":"SensorReportUpdateStatus":"PacketLength":"SensorStatus":"SensorReportingInterval":"SensorType":"GSM
ID":"Record start","S2, Main Kitchen
KE","000","3012,"RSSI","SensorOpticStatus","Record end":"Record
start","S2, Main Kitchen
KE","000","3012,"RSSI","SensorOpticStatus","Record end"


My aim is to get the "SiteName" and all the values starting from "GSM ID" into another string. The main issue is the length of the packet may vary after the "Record start" block based on the "SensorReportCount" value. if "SensorReportCount" = 2 then we will have the same packet copied above if the "SensorReportCount" = 3 then we will have an extra report which would look like something


"SiteName":"GPRSSignalStrength":"SelectedNetworkOperators":"GPRSReportingTimeOut":"SensorReportCount":"SensorReportUpdateStatus":"PacketLength":"SensorStatus":"SensorReportingInterval":"SensorType":"GSM
ID":"Record start","S2, Main Kitchen
KE","000","3012,"RSSI","SensorOpticStatus","Record end":"Record
start","S2, Main Kitchen
KE","000","3012,"RSSI","SensorOpticStatus","Record end":"Record
start","S2, Main Kitchen
KE","000","3012,"RSSI","SensorOpticStatus","Record end".


how is that possible to save "Site Name" and all the other blocks after "GSM ID" in another string.?

Answer

Use this regex:

^(.*?):.*("GSM ID".*)\.

See the Regex Demo

Use preg_match to get the submatches from the two capture groups. First capture group is for "SiteName" and the second is for everything after, and including, "GSM ID".

Comments