2017-07-13 319 views
0

我知道使用stripos()我可以在一个字符串搜索,如果此字符串包含了我想要的变量,return 'xx';变量搜索,返回“字符串,字符串2”上搜索

在以下4个字符串看看:

Power Red/Collegiate Burgundy 
Prism Pink,Racer Pink,Mist Blue,Prism Pink 
Red/Vintage White/Gold Metallic 
Sail,Pure Platinum,University Red,Obsidian 

所以这些都是'颜色'的变化,我有大约3000所有变化。

有一些关键字总是返回,如Red,Blue,Burgundy等等。

我想做到的是:

if (stripos($color_string, 'Red') !== false) { 
return 'Red';} 

但是有一个问题与此有关。使用上面的代码在包含Red的所有字符串上返回Red

什么,我想是这样的:

字符串Power Red/Collegiate Burgundy/Black Hard/Silver Paradise必须返回Red, Black, Burgundy, Silver

条形码输入将由我提供,包含所有不同的颜色变化。我希望我解释得很好!谢谢

+1

保持一个'$匹配= [];'阵列,而不是'回报 '红','你可以做'$匹配[] = '红','。然后,在函数结尾处,一旦完成所有匹配,返回implode(',',$ matches);' –

+0

*“上面的代码在所有包含红色的字符串上返回红色。”* - 我老实说不是很确定问题出在哪里。 – deceze

+0

Deceze,如果一个字符串包含'Red'而且'Blue',则stripos()不会返回红色,蓝色。它会返回2种颜色中的1种。 – Matthias

回答

0

分割字符串explode(),然后循环,返回所有的颜色匹配。您可以使用正则表达式而不是stripos()

$string = 'Power Red/Collegiate Burgundy/Black Hard/Silver Paradise'; 
$array = explode('/', $string); 
$colors = array_map(function($s) { 
    if (preg_match('/red|blue|black|burgundy|silver|pink/i', $s, $match)) { 
     return $match[0]; 
    } 
}, $array); 
print_r($colors); 

DEMO