regex 替换数组值PHP [duplicate]

wkyowqbh  于 2023-04-13  发布在  PHP
关注(0)|答案(3)|浏览(83)

此问题已在此处有答案

String replace all items in array PHP(3个答案)
5年前关闭。
我想改变数组中的最后一个“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
      )
aiqt4smr

aiqt4smr1#

$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];
    }
}
ezykj2lf

ezykj2lf2#

使用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 )
yebdmbv4

yebdmbv43#

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

$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 
)

相关问题