在preg_match_all的匹配中添加一个新的命名键

时间:2015-02-20 02:08:59

标签: php key preg-match-all

我的原始代码是:

$sc = 'hello 8491241 some text 6254841 some text 568241';
preg_match_all('/[0-9]{5,10}/', $sc, $matches1);

$all_matches = $matches1[0];

foreach ($all_matches as $match)
{
   $sid = '9';

   $rov['batch'] = $match;
   $rov['scid'] = $sid;
   $res[] = $rov;
}

print_r($res);

如何在preg_match_all的$ matches1中添加一个新的命名键['type'],在foreach中调用它并给我最终输出:

Array
(
    [0] => Array
        (
            [batch] => 8491241
            [type] => 1
            [scid] => 9
        )

    [1] => Array
        (
            [batch] => 568241
            [type] => 1
            [scid] => 9
        )

    [2] => Array
        (
            [batch] => 6254841
            [type] => 1
            [scid] => 9
        )
)
我试过的是:

$sc = 'hello 8491241 some text 6254841 some text 568241';
preg_match_all('/[0-9]{5,10}/', $sc, $matches1);

$pr_matches1['batch'] = $matches1[0];
$pr_matches1['type'] = 1;
$all_matches[] = $pr_matches1;

foreach ($all_matches as $match)
{
   $sid = '9';

   $rov['batch'] = $match['batch'];
   $rov['type'] = $match['type'];
   $rov['scid'] = $sid;
   $res[] = $rov;
}

print_r($res);

但它给了我错误的输出 http://pastebin.com/WXGpLTX9

请问好吗?

2 个答案:

答案 0 :(得分:2)

您可以使用array_map()来“扩展”每个匹配的项目:

$all_matches = array_map(function($match) {
    return [
      'batch' => $match,
      'type' => 1,
      'scid' => 9,
    ];
}, $matches1[0]);

答案 1 :(得分:0)

<?php

$sc = 'hello 8491241 some text 6254841 some text 568241';
preg_match_all('/[0-9]{5,10}/', $sc, $matches1);

$all_matches = $matches1[0];

foreach ($all_matches as $match)
{
   $rov['batch'] = $match;
   $rov['type'] = 1;
   $rov['scid'] = 9;
   $res[] = $rov;

}

print_r($res);

?>