str_replace() 不会替换更长、更理想的匹配字符串[重复]

问题描述 投票:0回答:2

我有两个数组。一个带有颜色名称,另一个带有 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

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

我看不出任何明显的原因说明为什么会发生这种情况,我错过了什么?

php string replace
2个回答
3
投票

那是因为

str_replace()
首先找到
yellow
(因为它在数组中的
Pale Yellow
之前),之后就再也找不到
Pale
了。因此,请使用
strtr()
来代替,如下所示:

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

1
投票

要解决此问题,请更改 $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');
© www.soinside.com 2019 - 2024. All rights reserved.