preg匹配所有数组搜索[]

时间:2013-08-08 12:25:30

标签: php arrays regex preg-match-all modbus

我找到了解决方案mysqlf使用:

foreach ($output as $value) {
    if (strpos($value, "]:") > -1) {
        $tal = substr($value, strpos($value, "]:") +3) . "<br>";
        echo $tal;
    }
}

返回: -210 -212


提前致谢。

我想要preg所以我只得到这条线:[10] =&gt; [147]: - 210 或两者[10] =&gt; [147]: - 210和[21] =&gt; [148]:-212

我如何预知[147]:或者是否有更好的方法来获取具体信息?

我的数组$ output包含:

Array
(
    [0] => modpoll 3.4 - FieldTalk(tm) Modbus(R) Master Simulator
    [1] => Copyright (c) 2002-2013 proconX Pty Ltd
    [2] => Visit http://www.modbusdriver.com for Modbus libraries and tools.
    [3] => 
    [4] => Protocol configuration: MODBUS/TCP
    [5] => Slave configuration...: address = 1, start reference = 147, count = 1
    [6] => Communication.........: 10.234.6.11, port 502, t/o 1.00 s, poll rate 1000 ms
    [7] => Data type.............: 16-bit register, output (holding) register table
    [8] => 
    [9] => -- Polling slave...
    [10] => [147]: -210
    [11] => modpoll 3.4 - FieldTalk(tm) Modbus(R) Master Simulator
    [12] => Copyright (c) 2002-2013 proconX Pty Ltd
    [13] => Visit http://www.modbusdriver.com for Modbus libraries and tools.
    [14] => 
    [15] => Protocol configuration: MODBUS/TCP
    [16] => Slave configuration...: address = 1, start reference = 148, count = 1
    [17] => Communication.........: 10.234.6.11, port 502, t/o 1.00 s, poll rate 1000 ms
    [18] => Data type.............: 16-bit register, output (holding) register table
    [19] => 
    [20] => -- Polling slave...
    [21] => [148]: -212
)

$matches  = preg_grep ('/^[147] (\w+)/i', $output);
print_r ($matches);
//only returns Array()

1 个答案:

答案 0 :(得分:0)

您需要转义左方括号,因为[147]被视为包含147

的字符类

你可以这样做:

$result=preg_grep('~^\[14(?:7|8)]:~',$rgData);
print_r($result);

您可以找到有关转义(或不转)方括号here

的所有信息