我有一个带有产品名称的字符串。此字符串也包含颜色。
示例:“红色T恤白黄色条纹黑点”($ productname)
PHP函数现在应该以字符串形式返回T恤的所有颜色。
我想我知道如何返回一种颜色,例如红色:
if (stripos($productname, 'red') !== false) {
return 'red';
}
如何返回所有颜色的字符串(逗号分隔)?在这种情况下,它应该是“红色,白色,黄色,黑色”。我有30种不同颜色的清单。
有人可以给我提示吗?
谢谢!
首先-您需要知道要找到什么颜色。
因此,必须定义您的颜色数组:
$colors = ['red', 'white', 'black', 'yellow', 'green'];
// create a regexp pattern from this array
// add `i` flag for turning off case sensistivity
$colors_regexp = '/(' . implode('|', $colors) . ')/i';
$matches = [];
$string = 'Red T-Shirt White Yellow Stripes Black Dots';
preg_match_all($colors_regexp, $string, $matches);
// print_r `$matches` to see the matches:
echo'<pre>',print_r($matches),'</pre>';
// use proper key from `$matches`:
echo implode(', ', $matches[0]); // `Red, White, Yellow, Black`
更进一步-您可以添加\b
含义,word boundary
以便其他词与您的正则表达式类似whitened
或blackened
不匹配:
preg_match_all(
'/\b(black|white|red)\b/i',
'White or red blackened item',
$matches
);
// matches[0] shows: `Array( [0] => White [1] => red )`, no `black`
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句