来自 str_replace() 的意外行为

Unexpected behavior from str_replace()

我有两个数组。一个带有颜色名称,另一个带有 RGB 值。

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

除了 Pale Yellow.

之外,所有颜色都按预期工作
$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

我不明白为什么它会在结果中选择 "Pale",这不是唯一的两个单词颜色,其他的都可以。

对于为什么会发生这种情况,我看不出任何明显的迹象,我错过了什么?

那是因为str_replace()先找到了yellow(因为它在数组中的Pale Yellow之前),之后就再也找不到Pale了。所以使用 strtr() 代替,像这样:

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

要解决此问题,请更改 $RGBint 数组中黄色/淡黄色的顺序。

正确:

$RGBint     = array('Red'      ,'Burgundy','Rust'     ,'Electric Orange','Pumpkin'    ,'Melon'     ,'Baby Pink'  ,'Candy Floss Pink','Electric Pink', 'Pale Yellow','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');