代码之家  ›  专栏  ›  技术社区  ›  hifi01

preg\u match\u all:更改字符串$match

  •  1
  • hifi01  · 技术社区  · 9 年前

    到目前为止:我正在做一个preg\u match\u all搜索,我的输出是:Donald,Daisy,Huey,Dewey和Louie

    $duckburg = array();
    preg_match_all($pattern,$subject,$match);
    $duckburg['residents'] = $match[1];
    print_r($duckburg['residents']);
    

    输出:

    Array ( [residents] => Array ( [0] => Donald [1] => Daisy [2] => Huey [3] => Dewey [4] => Louie )
    

    我的问题是:我想在每个字符串中添加“Duck”

    $lastname = " Duck"

    输出应为:

    Array ( [residents] => Array ( [0] => Donald Duck [1] => Daisy Duck [2] => Huey Duck [3] => Dewey Duck [4] => Louie Duck ) 
    

    我试过(但不起作用):

    preg_match_all($pattern,$subject,$match);
    $matchy = $match.$lastname;
    $duckburg['residents'] = $matchy[1];
    print_r($duckburg['residents']);
    

    2 回复  |  直到 9 年前
        1
  •  0
  •   Toto    9 年前

    Array_map

    $match = Array ( 'residents' => Array ('Donald','Daisy','Huey','Dewey','Louie'));
    $duckburg['residents'] = array_map(function($n) { return "$n Duck"; }, $match['residents']);
    var_dump($duckburg);
    

    array(1) {
      ["residents"]=>
      array(5) {
        [0]=>
        string(11) "Donald Duck"
        [1]=>
        string(10) "Daisy Duck"
        [2]=>
        string(9) "Huey Duck"
        [3]=>
        string(10) "Dewey Duck"
        [4]=>
        string(10) "Louie Duck"
      }
    }
    
        2
  •  0
  •   Cagy79    9 年前

    迭代数组是一种可能的选择:

    $lastname = " Duck";
    preg_match_all($pattern,$subject,$matches);
    foreach($matches as $key => $val){
        $duckburg['residents'][$key] = $val . $lastname;
    }
    print_r($duckburg['residents']);
    
    推荐文章