编程语言
首页 > 编程语言> > php – str_replace()的意外行为

php – str_replace()的意外行为

作者:互联网

我有两个数组.一个具有颜色名称,另一个具有RGB值.

我正在使用str_replace()将颜色名称转换为RGB值(然后用它做一些其他的东西).

除淡黄色外,所有颜色均按预期工作.

$colour = "Pale Yellow";
$RGBint     = array('Red'      ,'Burgundy','Rust'     ,'Electric Orange','Pumpkin'    ,'Melon'     ,'Baby Pink'  ,'Candy Floss Pink','Electric Pink','Yellow'    ,'Pale Yellow','Golden'    ,'Lime'     ,'Kiwi'       ,'Mint'       ,'Dragonfly Green','Kelly Green','Fern'       ,'Forest Green','Olive'     ,'Teal'      ,'Baby Blue'  ,'Dragonfly Blue','Cornflower' ,'Medium Blue','Royal Blue','Electric Blue','Navy'    ,'Lavender'   ,'Lilac'     ,'Purple'  ,'Plum'      ,'Dark Brown','Chocolate Brown','Light Brown','Copper'   ,'Beige'      ,'Linen'      ,'Taupe'      ,'Shimmer'    ,'Silver'     ,'Medium Grey','Charcoal'   ,'Black', 'White'     , 'Off White' , 'Neon Light Orange','Neon Orange','Neon Light Pink','Neon Dark Pink','Neon Yellow','Neon Green');
$ColourName = array("200,16,46","166,9,61","150,56,33","255,106,19"     ,"255,141,109","255,181,73","245,222,218","245,155,187"     ,"239,74,129"   ,"253,218,36","250,224,83" ,"203,160,82","206,220,0","142,221,101","128,224,167","169,196,127"    ,"0,132,61"   ,"142,221,101","0,87,63"     ,"103,130,58","39,153,137","171,202,233","189,214,230"   ,"123,175,212","95,143,180" ,"0,51,160"  ,"0,125,186"    ,"20,27,77","149,149,210","144,99,205","51,0,114","140,71,153","99,81,61"  ,"105,63,35"      ,"134,109,75" ,"115,56,29","219,200,182","176,170,126","138,126,112","208,211,212","162,172,171","142,144,137","112,115,114","0,0,0","255,255,255","227,223,195","255,170,77"        ,"255,143,108","255,95,162"     ,"239,66,111"    ,"224,231,33" ,"255,233,0");
$RGBvalue = str_replace($RGBint, $ColourName, $colour);
die($RGBvalue);

预期结果:

250,224,83

实际结果:

Pale 250,224,83

我不明白为什么它在结果中拾取“苍白”,这不是唯一的两个字颜色,其他工作正常.

关于为什么会这样,我什么都看不清楚,我错过了什么?

解决方法:

那是因为str_replace()首先找到黄色(因为它在数组中的淡黄色之前),然后它再也找不到Pale了.所以请改用strtr(),如下所示:

$RGBvalue = strtr($colour, array_combine($RGBint, $ColourName));

标签:str-replace,php,string
来源: https://codeday.me/bug/20191008/1874619.html