0
    <?php
$array1 = array(
                1 => "Lorem ipsum w1 lorem ipsum",
                2 => "Lorem ipsum w1 lorem ipsum",
                3 => "Lorem ipsum w1 lorem w1 ipsum",
                4 => "Lorem ipsum w1 lorem ipsum",
                5 => "Lorem ipsum w1 lorem ipsum",
                );
?>

How can I replace the word "w1" with another word "w2" and then generate a new array like

    <?php
    $array1 = array(
                1 => "Lorem ipsum w2 lorem ipsum",
                2 => "Lorem ipsum w2 lorem ipsum",
                3 => "Lorem ipsum w2 lorem w2 ipsum",
                4 => "Lorem ipsum w2 lorem ipsum",
                5 => "Lorem ipsum w2 lorem ipsum",
                );
?>

2 Answers 2

5
$res = array();
foeach($array1 as $key=>$val){
  $res[$key]   = str_replace("W1","W2",$val);
}

print_r($res);

Refer this for details about str_replace

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

1 Comment

you could skip the $res[$key] part and just use $val if your foreach is $key => &$val.
4

You can do this with either str_replace or preg_replace depending on how much functionality you need.

Both of these functions accept an array as their $subject argument, so it could be as simple as

$array1 = array(...); // strings with "w1"
$array1 = str_replace('w1', 'w2', $array1);

2 Comments

I would not recommend preg_replace for a simple task like this.
@DainisAbols: What is the simple task exactly? Obviously "w1" => "w2" is just an example. Perhaps in real life the regex \bw1\b would be needed?

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.