Reputation: 11
Trying to write a function to correct case of a set of anacroyms, but can't see how to do it more logically..
I have this at the moment
$str = str_ireplace(" worda ", " Worda ", $str);
$str = str_ireplace(" wordb ", " woRrdb ", $str);
and so on, its a long list!
Is there a way I could have a set of strings to replace with a set of replacements? Aka:
worda = Worda
wordb = woRdb
I've seen other examples using preg_replace too but can't see a way to do it using that function either.
Upvotes: 1
Views: 192
Reputation: 7795
Here's a way you can do it using an associative array:
$words = array('worda' => 'Worda', 'wordb' => 'woRdb');
$str = str_ireplace(array_keys($words), array_values($words), $str);
Upvotes: 0
Reputation: 15593
Hmm, Looks like you don't want to right write the function str_replace
multiple times.
So here is a solution for it:
you can take your data in an array like:
$arr = array("worda" => "Worda", "wordb" => "woRdb");
Hope this will be easy to do for you.
And then use the foreach
loop for it:
foreach($arr as $key => $value){
$str = str_ireplace($key, $value, $str);
}
Upvotes: 0
Reputation: 26451
You can give list of words in array as a parameter in str_ireplace,
$str = str_ireplace(array("worda","wordb"),array("Worda","woRrdb"),$str);
More beautifully,
$searchWords = array("worda","wordb");
$replaceWords = array("Worda","woRrdb");
$str = str_ireplace($searchWords,$replaceWords,$str);
Upvotes: 1