2017-01-12 4 views
0

商品名の文字列があります。この文字列には色も含まれています。PHPで他の文字列からあらかじめ選択した単語の文字列を返します

例:「赤いTシャツホワイトイエロー・ストライプスの黒点」($のPRODUCTNAME)

PHP関数は現在の文字列でTシャツのすべての色を返す必要があります。

私は赤い例えば、一つの色を返す方法を知っていると思う:

if (stripos($productname, 'red') !== false) { 
    return 'red'; 
} 

私はすべての色(カンマ区切り)で文字列を返すことができますどのように?この場合、「赤、白、黄、黒」でなければなりません。私は30種類の色のリストを持っています。

誰かが私にヒントを与えることはできますか?

ありがとうございます!

+1

は、正規表現を作成し、 'preg_match_all'を使用する:あなたが持っている場合など、複数のスペース、タブや改行がexplode()の代わりにこれを使用します –

答えて

2

まず最初に、どの色を見つけるかを知る必要があります。

だから、あなたの色の配列を定義する必要があります。

$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` 
0

foreachループを使用して、すでに単一の色ごとに表示されているかどうかを確認することができます。

最後のカンマを削除します) RTRIM(:

function check_colour($productname, $colours){ 

    foreach ($colours as $colour) { 
     if (stripos($productname, $colour) !== false) { 
      $output .= $colour.","; 
     } 
    } 
    $out = rtrim($output, ','); 

    return $out 
} 

$productname = "Red T-Shirt White Yellow Stripes Black Dots"; 

$colours = new array("Red", "White", "Yellow", "Black", "Green"); 

echo check_colour($productname); 

EDIT:

function check_colour($productname){ 

    $colours = new array("Red", "White", "Yellow", "Black", "Green"); 

    foreach ($colours as $colour) { 
     if (stripos($productname, $colour) !== false) { 
      $output .= $colour.","; 
     } 
    } 
    $out = rtrim($output, ','); 

    return $out 
} 

$productname = "Red T-Shirt White Yellow Stripes Black Dots"; 

echo check_colour($productname); 

が、私はそれを簡単に呼び出すことができるように機能に入れて、あなたはまた、色も引数であることをそれを作ることができます

0

色の配列を使用しているため、異なるアプローチです。文字列から単語の配列を作成し、交差点(一般的な単語)を見つけるだけです。ケース非感受性のための例は、同じにするためにarray_map()を使用します。

$string = "Red T-Shirt White Yellow Stripes Dots"; 
$colors = array("Red", "White", "Yellow", "Black"); 

$result = array_intersect(array_map('strtolower', $colors), 
          array_map('strtolower', explode(' ', $string))); 

print_r($result); 
//or 
echo implode(', ', $result); 

は、これは1つのスペースで文字列を分割します。

preg_split('/\s+/', $string); 
関連する問題