gerkintrigg Posted November 14, 2009 Share Posted November 14, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/181505-solved-case-sensitive-replacing-of-strings/ Share on other sites More sharing options...
Alex Posted November 14, 2009 Share Posted November 14, 2009 How do you expect that to work? Not all words are the same length. Quote Link to comment https://forums.phpfreaks.com/topic/181505-solved-case-sensitive-replacing-of-strings/#findComment-957473 Share on other sites More sharing options...
Garethp Posted November 14, 2009 Share Posted November 14, 2009 $Search = array( 'word', 'Word', 'WORD' ); $Replace = array( 'replacement', 'Replacement', 'REPLACEMENT' ); $Str = str_replace($Search, $Replace, $Str); [/code] Should work Quote Link to comment https://forums.phpfreaks.com/topic/181505-solved-case-sensitive-replacing-of-strings/#findComment-957475 Share on other sites More sharing options...
gerkintrigg Posted November 15, 2009 Author Share Posted November 15, 2009 excellent, thanks. if a word is LiKe ThIs... they're just going to need to be ignored... I can't be doing with getting around that one too! Quote Link to comment https://forums.phpfreaks.com/topic/181505-solved-case-sensitive-replacing-of-strings/#findComment-957842 Share on other sites More sharing options...
gerkintrigg Posted November 15, 2009 Author Share Posted November 15, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/181505-solved-case-sensitive-replacing-of-strings/#findComment-957843 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.