Jump to content

[SOLVED] case sensitive replacing of strings


gerkintrigg

Recommended Posts

This one is slightly tricky...

I want to search through a string and replace a word.

 

So let's imagine that I'm using this code:

str_replace($word,$replacement_word,$string);

 

How can I replace the word, but still maintain its case?

 

For example if the word is "WORD" then the replacement would be "REPLACEMENT"

If the word is: "word", the replacement is "replacement"

If the word is: "Word", the replacement is "Replacement"

 

I want to do this against a database of words eventually but if I can work out how to do it with one, then I can work out the rest myself.

Here's the final code:

$Str='replace this Word, that word and the other WORD with stuff.';
$word='word';
$Search = array(
$word,
ucwords($word),
strtoupper($word)
);

$replacement_word='thingie';
$Replace = array(
$replacement_word,
ucwords($replacement_word),
strtoupper($replacement_word)
);

$Str = str_replace($Search, $Replace, $Str);
echo $Str

 

When I put this into a while loop from my database select querie, it can specify the $word and $replacement variables with database information.

 

That's exactly what I wanted and it even works! *lol*

 

Thanks for that. All I need to do now is ensure that the database is only filled with lower case info.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.