まず最初に、どの色を見つけるかを知る必要があります。
だから、あなたの色の配列がを定義する必要があります。
$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`
はさらに行く - あなたはwhitened
またはblackened
のような他の言葉があなたの正規表現と一致しませんようにword boundary
を意味している\b
を追加することができます。
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`
は、正規表現を作成し、 'preg_match_all'を使用する:あなたが持っている場合など、複数のスペース、タブや改行が
explode()
の代わりにこれを使用します –