PHP-为什么str_replace无法正确替换
作者:互联网
这是我的剧本
$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
解决方法:
出现意外结果的原因是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
标签:str-replace,php 来源: https://codeday.me/bug/20191013/1904713.html