替换数组值PHP

时间:2018-03-30 10:32:45

标签: php arrays regex php-7

我想改变最后的" S"数组值中的字母。我尝试了很多方法,但仍然无法工作。

这是我的代码():

<?php
$array = array ("romeo/echos/julion/1991s/1992.jpg",
                "romeo/echos/julion/1257s/1258.jpg",
                "romeo/echos/julion/1996s/1965.jpg",
);

foreach ($array as $key => $value) {
    if ($key == "romeo/echos/julion/'.*?'s/'.*?'.jpg") 
         $value="romeo/echos/julion/'.*?'l/'.*?'.jpg";
}

print_r($value);
?>

我希望价值看起来像这样:

Array ( [0] => romeo/echos/julion/1991l/1992.jpg 
        [1] => romeo/echos/julion/1257l/1258.jpg 
        [2] => romeo/echos/julion/1996l/1965.jpg
      ) 

3 个答案:

答案 0 :(得分:0)

$value是数组元素的副本,因此分配给它不会修改数组。如果使用引用变量,它将更新数组。

另外,您没有正确测试该值。首先,当您使用==来测试正则表达式模式时,您正在使用preg_match()。您正在测试$key而非$value(密钥只是索引012等。)

foreach ($array as &$value) {
    if (preg_match('#(romeo/echos/julion/.*?)s(/.*?.jpg)#', $value, $match)) {
        $value = $match[1] . "l" . $match[2];
    }
}

答案 1 :(得分:0)

我测试了以下内容,它提供了您想要的确切输出。

$array = array("romeo/echos/julion/1991s/1992.jpg",
            "romeo/echos/julion/1257s/1258.jpg",
            "romeo/echos/julion/1996s/1965.jpg");

$replace = str_replace("s/1", "l/1", $array);
    print_r($replace);  
}

输出:

Array ( 
    [0] => romeo/echos/julion/1991l/1992.jpg 
    [1] => romeo/echos/julion/1257l/1258.jpg 
    [2] => romeo/echos/julion/1996l/1965.jpg 
)

答案 2 :(得分:0)

使用str_replace()

  <?php
    $array = array ("romeo/echos/julion/1991s/1992.jpg",
                    "romeo/echos/julion/1257s/1258.jpg",
                    "romeo/echos/julion/1996s/1965.jpg",
    );

    foreach ($array as $key => $value) {

      $arr[]=str_replace('s/1','l/1',$value);
    }

    print_r($arr);
    ?>

输出:

Array ( [0] => romeo/echos/julion/1991l/1992.jpg [1] => romeo/echos/julion/1257l/1258.jpg [2] => romeo/echos/julion/1996l/1965.jpg )