user632347
user632347

Reputation: 835

How to replace words in an array's value with another

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

Upvotes: 0

Views: 180

Answers (2)

Prasanth Bendra
Prasanth Bendra

Reputation: 32830

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

print_r($res);

Refer this for details about str_replace

Upvotes: 5

Jon
Jon

Reputation: 437854

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

Upvotes: 4

Related Questions