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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.