1

I want to change the 'S' from the array into 'l'. but it won't work. Please help me with this one.

Here's my code:

<?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);
?>
1
  • str_replace function. Commented Mar 30, 2018 at 8:46

3 Answers 3

1

1. You need to use str_replace() along with call by reference

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

print_r($array);

Output:- https://eval.in/981246

2. Or you can directly go to 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);
?>

Output:- https://eval.in/981225

3 Or go with preg_replace()

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

Output:- https://eval.in/981245

Sign up to request clarification or add additional context in comments.

2 Comments

i've deleted my answer. so is this okay if i post it (i mean my last answer that i've deleted) to another question?
@RheyzaVirgiawanD'first you can ask a new question anytime. But try to clarify your question clearly that what exactly you want and what isn't working? Also, don't forget to post your code effort too. Thanks
0

You can try like this way,

$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>';

Output:

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

DEMO: https://eval.in/981216

Comments

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

Result:

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.