Reputation: 835
<?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
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
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