I have a page that generates a form with the words “Grant” and “Revoke” in it multiple times. I’m trying to replace every instance of “Grant” with “Revoke” and vice-versa. For example, I would like this:
Grant - Asset 1 - User 1
Revoke - Asset 2 - User 1
Revoke - Asset 3 - User 1
Revoke - Asset 4 - User 1
Grant - Asset 5 - User 1
Grant - Asset 6 - User 1
To be turned into this:
Revoke - Asset 1 - User 1
Grant - Asset 2 - User 1
Grant - Asset 3 - User 1
Grant - Asset 4 - User 1
Revoke - Asset 5 - User 1
Revoke - Asset 6 - User 1
But when I use str_replace to do this, I just end up with all of the instances being turned into either “Grant” or “Revoke”, depending on which string I replace last.
The only way I can think of is a bit messy, but it’s what I would do using search and replace in a word processing document, and it’s the same principle.
Thanks for your response. Unfortunately, I need to be able to do it programmatically. I was thinking maybe I could track where the strings start/end in the document using strpos, then only replace those characters, but I was hoping someone would have a better method.
I often use strtr much more than any other string replacement functions. I find doing a simple array and doing a quick conversion using strtr much easier and faster than trying to use Regex or writing a very lengthy function to do the exact same thing.
Of course. I wasn’t suggesting that you use a word processor to do the job, just that it’s much the same process as you would do a global copy and replace. In my example, you would just run str_replace() 3 times. However, you have a more efficient and more elegant solution now!