String replace


#1

Hello,

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.

Does anyone know of a way to accomplish this?

Thanks in advance.


#2

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.

  1. change all instances of Grant to (say) xyzxyz
  2. change all instances of Revoke to Grant
  3. change all instances of xyzxyz to Revoke

#3

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.


#4

Can’t it be done by putting arrays into the search and replace parameters?

$words = array('Grant', 'Revoke');

$result = str_replace($words, array_reverse($words), $string);

I’ve not tested this code, but I think it should work.


#5

strtr works perfectly for these kind of things:

$content = strtr($content, [
    'Grant' => 'Revoke',
    'Revoke' => 'Grant',
]);

#6

Awesome, thank you so much, that worked great. :slight_smile:


#7

Many thanks,

I really like that script, so simple but very effective :slight_smile:


#8

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.


#9

I would be grateful for a couple of examples :slight_smile:


#10

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! :slightly_smiling_face:


#11

@ScallioXTX already showed a pretty good example. But I normally do something like

$variable = 'This is spaceshiptrooper';

$variable = strtr($variable, ['spaceshiptrooper' => 'John_Betong']);

#12

Whoops, I was getting confused with strstr(…) instead of strtr(…).

It’s been one of those days :frowning: