str_replace()

时间:2015-04-27 09:19:03

标签: php string 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

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

我看不清楚为什么会发生这种情况,我错过了什么?

2 个答案:

答案 0 :(得分:3)

这是因为str_replace()首先找到yellow(因为它在数组中Pale Yellow之前)并且在此之后它无法找到{{} 1}}了。所以请改用strtr(),如下所示:

Pale

答案 1 :(得分:1)

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

正确:

revertFunc