Search code examples
phparraysregexphp-7

Replacing array value PHP


i want to change the last "S" letter in array value. i've try many ways but still wont work.

here's my code ():

<?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);
?>

i want the value look like this :

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

Solution

  • $value is a copy of the array element, so assigning to it doesn't modify the array. If you use a reference variable it will update the array.

    Also, you're not testing the value correctly. First, you're using == when you should be using preg_match() to test a regular expression pattern. And you're testing $key instead of $value (the keys are just indexes 0, 1, 2, etc.)

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