2017-03-20 46 views
0

例数组项的字符串:匹配其中包含与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

秀应该如何看待预期结果 – RomanPerekhrest

+0

我想帮助你,但是你的过程的总体目标是什么?你是否试图根据值的长度来验证字符串? – mickmackusa

回答

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'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, 
    ), 
), 
)