替换某些数组值

时间:2018-03-30 08:42:41

标签: php arrays regex

我想将数组中的'S'更改为'l'。但它不会起作用。 请帮帮我。

这是我的代码:

<?php
    $array = array (
        "romeo/echo/julion/1991s/1992.jpg",
        "romeo/echo/julion/1257s/1258.jpg",
        "romeo/echo/julion/1996s/1965.jpg",
    );
    foreach($array as $key => $value){
        if($key == "romeo/echo/julion/'.*?'s/'.*?'.jpg") $value="romeo/echo/julion/'.*?'l/'.*?'.jpg";
    }
    print_r($value);
?>

3 个答案:

答案 0 :(得分:1)

1。 您需要使用str_replace()以及call by reference

foreach ($array as &$value) {
  $value = str_replace('s/','l/',$value);
}

print_r($array);

输出: - https://eval.in/981246

2。 或者您可以直接转到array_map()

<?php
function strReplace($n)
{
    return(str_replace('s/','l/',$n));
}

$array = array ("romeo/echo/julion/1991s/1992.jpg",
                "romeo/echo/julion/1257s/1258.jpg",
                "romeo/echo/julion/1996s/1965.jpg",
);
$final_array = array_map("strReplace", $array);
print_r($final_array);
?>

输出: - https://eval.in/981225

3 或使用preg_replace()

$array = preg_replace('/(\d{4})(s\/)/', '$1l/', $array);

输出: - https://eval.in/981245

答案 1 :(得分:0)

你可以这样试试,

var ulcontainer = $('<ul></ul>');
	    $('body').append(ulcontainer);
	    $ ('ul').css('list-style','none');
	
	for (var i = 0; i < 3; i++) {
			dothis();
	}
function dothis()
{
	$('ul').append("<li></li>")

	var imgdiv = $('<div></div>').text("this is imgdiv"); /// prod

	var detaildiv = $('<div></div>').text("this is detailsdiv"); ///price of prod
	var closebtndiv = $('<div></div>').text("this is closebtndiv");
	$('li').append(imgdiv,detaildiv,closebtndiv,"<br>");
	$('li').css({'padding':'20px'});		
	$('div').css({'display':'inline','padding':'20px'});
	
}

<强>输出:

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


$array = preg_replace("/(s)(?=\/)/", "l", $array);
print '<pre>';
print_r($array);
print '</pre>';

DEMO: https://eval.in/981216

答案 2 :(得分:0)

$array = [
    "romeo/echo/julion/1991s/1992.jpg",
    "romeo/echo/julion/1257s/1258.jpg",
    "romeo/echo/julion/1996s/1965.jpg",
];

$array = preg_replace('/(\d{4})(s)/', '$1l', $array);

结果:

array(3) {
    [0] =>
    string(32) "romeo/echo/julion/1991l/1992.jpg"
    [1] =>
    string(32) "romeo/echo/julion/1257l/1258.jpg"
    [2] =>
    string(32) "romeo/echo/julion/1996l/1965.jpg"
}