【问题标题】:preg_match_all: changing the string $matchpreg_match_all:更改字符串 $match
【发布时间】:2017-07-25 11:20:31
【问题描述】:

到目前为止:我正在进行 preg_match_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']);

是否可以在匹配字符串进入数组之前更改它?感谢您的帮助!

【问题讨论】:

  • 使用$duckburg['residents'] = $matchy;而不是$duckburg['residents'] = $matchy[1];

标签: php preg-match-all


【解决方案1】:

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】:

    遍历数组是一种可能的选择:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 2018-05-07
      • 1970-01-01
      • 2021-12-19
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多