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
      ) 
1
  • 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 instead. Commented Mar 30, 2018 at 10:34

3 Answers 3

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];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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 )

Comments

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 
)

5 Comments

Please read question carefully.
@LawrenceCherone Answer fixed :)
@LawrenceCherone better ?
Bad form, just copying from mine.
huh? copy from your what ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.