I am on a site where I am looking for replacing 2 strings with each other.
I have 2 strings called Cart and Bag. I want to change where it is Cart, it’ll be replaced with Bag and where it is Bag, it’ll be replaced with Cart.
I have used the below PHP code to change strings:
add_filter( 'gettext', function ( $strings ) {
$text = array(
'Bag' => 'Cart',
'Cart' => 'Bag',
);
$strings = str_ireplace( array_keys( $text ), $text, $strings );
return $strings;
}, 20 );
Which as a result shows al the Cart and Bag strings as Bag.
Can anyone please guide me what correction can be done here?
Or any script that can help?
TIA.
2
Answers
Let’s take an example of
$strings
.str_ireplace
searches the gives needles one by one and replaces them with the respective value from the replacements array (passed as the 2nd parameter) .So, in this process, the string becomes,
Although there are multiple ways to solve this issue, I would prefer the below approach.
$text
.Snippet:
Online Demo
Split the string into an array then replace cart with bag and vice-versa, and join the array again.