英文:
Change strings using script
问题
我在一个网站上,正在寻找用一个字符串替换另一个字符串的方法。
我有两个字符串分别叫做Cart和Bag。我想把所有Cart替换为Bag,把所有Bag替换为Cart。
我使用了以下的PHP代码来进行字符串替换:
add_filter( 'gettext', function ( $strings ) {
$text = array(
'Bag' => 'Cart',
'Cart' => 'Bag',
);
$strings = str_ireplace( array_keys( $text ), $text, $strings );
return $strings;
}, 20 );
结果是所有的Cart和Bag字符串都显示为Bag。
请问有人可以指导我应该如何进行修正吗?
或者是否有其他的脚本可以帮助我?
TIA.
英文:
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.
答案1
得分: 3
让我们以$strings
的示例开始。
Bag Cart Cart Bag
str_ireplace
逐个搜索给定的针对,并将它们替换为替代数组中的相应值(作为第二个参数传递)。
因此,在这个过程中,字符串变成了:
1 --> Cart Cart Cart Cart
2 --> Bag Bag Bag Bag
虽然有多种解决此问题的方法,但我更喜欢以下方法。
- 根据空格拆分字符串。
- 使用
array_map
将拆分数组的每个值与$text
中的值进行映射。 - 将数组合并回字符串。
代码片段:
<?php
$strings = implode(" ", array_map(fn($v) => $text[$v] ?? $v, explode(" ", $strings)));
英文:
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)));
答案2
得分: 0
将字符串拆分为一个数组,然后将"cart"替换为"bag",将"bag"替换为"cart",然后再将数组连接起来。
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)
请注意,这是JavaScript代码的翻译。
英文:
Split the string into an array then replace cart with bag and vice-versa, and join the array again.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论