0

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
      ) 
  • I haven't checked your regex, but the point is you can't apply a regex using `==` and a substitution by assigning a value containing a regex. You can get rid of the `if` and use [`preg_replace`](http://php.net/manual/en/function.preg-replace.php) instead. – Federico klez Culloca Mar 30 '18 at 10:34

3 Answers3

0

$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];
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I have tested the following and it provides the exact output you would like.

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

outputs :

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

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

output:

Array ( [0] => romeo/echos/julion/1991l/1992.jpg [1] => romeo/echos/julion/1257l/1258.jpg [2] => romeo/echos/julion/1996l/1965.jpg )
R B
  • 658
  • 4
  • 12