这是我的剧本
$searchArray = array("Coupon Codes", "Coupon Code", "Promo", "Promo Codes");
$replaceArray = array("Promo Code", "Promo Codes", "Coupons", "Coupon Code");
$intoString = "Best Buy Coupon Codes";
print str_replace($searchArray, $replaceArray, $intoString);
结果:百思买优惠券代码
预期输出:百思买促销代码
PHP版本5.6.36
答案 0 :(得分:3)
出现意外结果的原因是str_replace
首先将“优惠券代码”替换为“促销代码”,然后再将“促销”替换为“优惠券”。要解决此问题,请使用strtr
的数组形式,它将首先处理最长的字符串,但最重要的是不会替换为任何先前替换的文本。例如
$searchArray = array("Coupon Codes", "Coupon Code", "Promo", "Promo Codes");
$replaceArray = array("Promo Code", "Promo Codes", "Coupons", "Coupon Code");
$intoString = "Best Buy Coupon Codes";
// this doesn't work
echo str_replace($searchArray, $replaceArray, $intoString);
// this does
echo strtr($intoString, array_combine($searchArray, $replaceArray));
输出:
Best Buy Coupons Code
Best Buy Promo Code
答案 1 :(得分:1)
截至: http://php.net/manual/en/function.str-replace.php
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
这就是发生的事情:
百思买优惠券代码->百思买促销代码(第一对)->百思买优惠券代码(第三对)
更改$searchArray
(和$replaceArray
)的方式应使下一个示例中不包含先前的示例(即从最短字符串到最长字符串)