1

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.

3 Answers 3

1

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); 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

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.