将包含数组项的字符串与preg_match_all

时间:2017-03-20 06:51:48

标签: php regex preg-match-all

示例:

我有这个字符串

"  [mc_gross] => 50.00  [invoice] => done  [address_details] => xyz  [protection_eligibility] => Eligible"

所以,我使用了以下代码。

preg_match_all("/^\s{2}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

Preg_match_all返回空数组,但我想返回类似下面数组的偏移值:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] =>   [mc_gross] =>
                    [1] => 0
                )
            [1] => Array
                (
                    [0] => mc_gross
                    [1] => 3
                )
        )
    [1] => Array
          (
            [0] => Array
                (
                    [0] =>   [invoice] =>
                    [1] => 21
                )
            [1] => Array
                (
                    [0] => invoice
                    [1] => 24
                )
        )

)

这样我就可以测试以下代码:

foreach($matches as $match) {
     $key = $match[1][0]; // matched string
     $offset = $match[0][1]; // starting point of the matched string
     // start returns starting point of matched string + string length of matched string
     $start = $match[0][1] + strlen($match[0][0]);
}

1 个答案:

答案 0 :(得分:1)

我只使用了你的一个标志,修改了正则表达式模式,并从数组中取消设置完全匹配(匹配[0]),然后重置键。

这提供了一个类似于您的请求但具有干净键值的数组:

$in="  [mc_gross] => 50.00  [invoice] => done  [address_details] => xyz  [protection_eligibility] => Eligible  ";
if(preg_match_all("/\[([^]]*?)\]\s=>\s(.*?)\s{2}/", $in, $matches, PREG_OFFSET_CAPTURE)){
    unset($matches[0]);
    $matches=array_values($matches);
    echo "<pre>";
    var_export($matches);
    echo "</pre>";
}else{
    echo "no match";
}

带有解释的正则表达式模式Demo

这是var_export&#39; ed数组:

array (
  0 => 
  array (
    0 => 
    array (
      0 => 'mc_gross',
      1 => 5,
    ),
    1 => 
    array (
      0 => 'invoice',
      1 => 26,
    ),
    2 => 
    array (
      0 => 'address_details',
      1 => 45,
    ),
    3 => 
    array (
      0 => 'protection_eligibility',
      1 => 71,
    ),
  ),
  1 => 
  array (
    0 => 
    array (
      0 => '50.00',
      1 => 18,
    ),
    1 => 
    array (
      0 => 'done',
      1 => 38,
    ),
    2 => 
    array (
      0 => 'xyz',
      1 => 65,
    ),
    3 => 
    array (
      0 => 'Eligible',
      1 => 98,
    ),
  ),
)