根据PHP的长度切断并获取字符串的值

时间:2016-04-26 09:42:47

标签: php regex

这个问题可能看起来有点奇怪,因为它从昨天开始一直在吹我的脑海。我从TCP / IP数据包中得到一个字符串,就像这样..

  

“网站名”: “GPRSSignalStrength”: “SelectedNetworkOperators”: “GPRSReportingTimeOut”: “SensorReportCount”: “SensorReportUpdateStatus”: “PacketLength”: “SensorStatus”: “SensorReportingInterval”: “SensorType”:“GSM   ID“:”记录开始“,”S2,主厨房   KE“,”000“,”3012,“RSSI”,“SensorOpticStatus”,“记录结束”:“记录   开始“,”S2,主厨房   KE“,”000“,”3012,“RSSI”,“SensorOpticStatus”,“记录结束”

我的目标是将“SiteName”和从“GSM ID”开始的所有值转换为另一个字符串。主要问题是在“记录开始”块之后,根据“SensorReportCount”值,数据包的长度可能会有所不同。如果“SensorReportCount”= 2,那么如果“SensorReportCount”= 3,我们将在上面复制相同的数据包,那么我们将有一个额外的报告看起来像什么

  

“网站名”: “GPRSSignalStrength”: “SelectedNetworkOperators”: “GPRSReportingTimeOut”: “SensorReportCount”: “SensorReportUpdateStatus”: “PacketLength”: “SensorStatus”: “SensorReportingInterval”: “SensorType”:“GSM   ID“:”记录开始“,”S2,主厨房   KE“,”000“,”3012,“RSSI”,“SensorOpticStatus”,“记录结束”:“记录   开始“,”S2,主厨房   KE“,”000“,”3012,“RSSI”,“SensorOpticStatus”,“记录结束”:“记录   开始“,”S2,主厨房   KE“,”000“,”3012,“RSSI”,“SensorOpticStatus”,“记录结束”。

如何在另一个字符串中保存“站点名称”和“GSM ID”之后的所有其他块。?

2 个答案:

答案 0 :(得分:0)

使用此正则表达式:

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

请参阅Regex Demo

使用preg_match从两个捕获组中获取子匹配。第一个捕获组用于" SiteName"第二个是所有事情,包括" GSM ID"。

答案 1 :(得分:0)

<强>字符串

$text = '"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"';

PHP常规表达

$pattern = '[^(.+?:).+("GSM ID":.+)]';
preg_match_all($pattern, $text, $out);

对于您需要使用+而不是*原因的模式,+检查1或更多,这意味着如果找到。

<强>结果

Array
(
    [0] => Array
        (
            [0] => "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"
        )

    [1] => Array
        (
            [0] => "SiteName":
        )

    [2] => Array
        (
            [0] => "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"
        )

)

连接数组索引1和2后,结果将相同。

PHP爆炸

$arr = explode(':"GSM ID"', $text);

echo '"SiteName":"GSM ID"'.$arr[1];

<强>输出:

  

&#34; SiteName&#34;:&#34; GSM ID&#34;:&#34;记录开始&#34;,&#34; S2,主厨房   KE&#34;,&#34; 000&#34;,&#34; 3012,&#34; RSSI&#34;,&#34; SensorOpticStatus&#34;,&#34;记录结束&#34;:&# 34;记录   开始&#34;,&#34; S2,主厨房   KE&#34;,&#34; 000&#34;,&#34; 3012,&#34; RSSI&#34;,&#34; SensorOpticStatus&#34;,&#34;记录结束&#34;