skip to Main Content

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


  1. Let’s take an example of $strings.

    Bag Cart Cart Bag
    

    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,

    1 --> Cart Cart Cart Cart
    2 --> Bag  Bag  Bag  Bag
    

    Although there are multiple ways to solve this issue, I would prefer the below approach.

    • Explode the string based on space.
    • Use array_map to map each value from the exploded array with regards to value from $text.
    • Implode the array back to the string.

    Snippet:

    <?php
    
    $strings = implode(" ", array_map(fn($v) => $text[$v] ?? $v, explode(" ", $strings)));
    

    Online Demo

    Login or Signup to reply.
  2. Split the string into an array then replace cart with bag and vice-versa, and join the array again.

    const str = "This is a cart and bag, cart is cart and bag is bag"
    let arr = str.split(" ");
    let r = arr.map((s) => s.includes('cart') ? s.replace('cart', 'bag') : s.includes('bag') ? s.replace('bag', 'cart') : s)
    
    let ans = r.join(" ")
    console.log(ans)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search