在PHP中从String中提取某些字符

时间:2015-07-22 01:30:34

标签: php regex

我在数据库中有多行,如下所示

Retractor Color: Blue
Robin Jacket Color: Black (Body) & Red (Stripe)Size: L 
Ladies Clutch in Green   
T-Shirt  Color: BlackSize: L 
Full Sleeve Sweat Shirt Color: Grey Melange (Light Grey)Size: S 
T-Shirt  Color: BlackSize: L
Speed Jacket  Size: M

我需要将每行的颜色和大小信息提取到一个单独的列中以便轻松识别。由于我不擅长正则表达式,有人可以帮助我如何实现这一点。

编辑:

我需要输出如下 enter image description here

2 个答案:

答案 0 :(得分:2)

如果没有一致的格式,并且您需要匹配随机颜色字符串,则需要列出所有可能的颜色。如果你把“melange”称为一种颜色,那可能会很难,我认为这不是用谷歌搜索那个词。无论如何想出你可以期待的颜色,并检查它们是否存在于字符串中。

正则表达式中具有颜色匹配的版本。

<?php

$colors = ['Red', 'Orange', 'Yellow', 'Black', 'Blue', 'Grey'];
$colorStr = implode('|', $colors);
$colorPattern = "/({$colorStr})/i";

$sizePattern = '/Size: (\w+)/i';

$rows = [
'Retractor Color: Blue',
'Robin Jacket Color: Black (Body) &amp; Red (Stripe)Size: L',
'Ladies Clutch in Green',
'T-Shirt  Color: BlackSize: L',
'Full Sleeve Sweat Shirt Color: Grey Melange (Light Grey)Size: S',
'T-Shirt  Color: BlackSize: L',
'Speed Jacket  Size: M'
];

$output = [];

foreach($rows AS $row){
   $data = ['product'=>$row];

   preg_match($colorPattern, $row, $colorsFound);
   if(isset($colorsFound[1])){
     array_shift($colorsFound);
     $data['colors'] = $colorsFound;
   }

   preg_match($sizePattern, $row, $sizes);
   if(isset($sizes[1])){
      $data['size'] = $sizes[1];
   }
   $output[] = $data;
}

var_dump($output);

https://eval.in/402722

(我的原始版本在下面,正则表达式是更好的。)

<?php

$colors = ['Red', 'Orange', 'Yellow', 'Black', 'Blue', 'Grey'];

$rows = [
'Retractor Color: Blue',
'Robin Jacket Color: Black (Body) &amp; Red (Stripe)Size: L',
'Ladies Clutch in Green',
'T-Shirt  Color: BlackSize: L',
'Full Sleeve Sweat Shirt Color: Grey Melange (Light Grey)Size: S',
'T-Shirt  Color: BlackSize: L',
'Speed Jacket  Size: M'
];

$output = [];

foreach($rows AS $row){
   $data = ['product'=>$row];
   foreach($colors AS $color){
      if(stripos($row, $color) !== false){
         $data['colors'][] = $color;
      }
   }
   preg_match('/Size: (\w+)/', $row, $matches);
   if(isset($matches[1])){
      $data['size'] = $matches[1];
   }
   $output[] = $data;
}

https://eval.in/402712

答案 1 :(得分:0)

我的解决方案使用explodestr_replacepreg_replace的组合进行解析,并具有以下功能:

  • 您无需为可能的颜色或尺寸选项定义数组。您可以使用任何颜色字符串和任何大小值
  • 所有行都有三个列。
    • 空列的值为NULL
  • 您可以同时使用Color:in来定义颜色值
    • 对于所有颜色值,删除任何( )及其内容
    • 对于所有颜色值,&amp;将替换为,

演示:

https://eval.in/402731

代码:

<?php

$string = "Retractor Color: Blue
Robin Jacket Color: Black (Body) &amp; Red (Stripe)Size: L 
Ladies Clutch in Green   
T-Shirt  Color: BlackSize: L 
Full Sleeve Sweat Shirt Color: Grey Melange (Light Grey)Size: S 
T-Shirt  Color: BlackSize: L
Speed Jacket  Size: M";

// Split string on new line character
$data = explode("\n", $string);
$output = [];
// Loop through lines
foreach ($data as $i => $value) {
    $value = trim($value);
    // Split string on "Color: "
    $data[$i] = explode("Color: ", $value);
    // If color value is not found
    if (count($data[$i]) < 2) {
        // Split string on " in "
        $data[$i] = explode(" in ", $data[$i][0]);
    }
    // If color value is still not found
    if (count($data[$i]) < 2) {
        // Split string on "Size: "
        $data[$i] = explode("Size: ", trim($data[$i][0]));
        //Build output
        $output[$i] = ['Product' => $value, 'Color' => null, 'Size' => $data[$i][1]];
    } else {
        // Split string on "Size: "
        $data[$i] = explode("Size: ", trim($data[$i][1]));
        //Remove " (__) " and replace " &amp ";
        $data[$i][0] = preg_replace('/[ ]?[\(].*[\)][ ]?/U', '', str_replace(' &amp; ', ',', $data[$i][0]));
        // If size value is not found
        if (count($data[$i]) < 2) {
            // Set NULL value for missing Size
            $data[$i][1] = NULL;
        }
        // Build output
        $output[$i] = ['Product' => $value, 'Color' => $data[$i][0], 'Size' => $data[$i][1]];
    }
}

var_dump($output);
?>

输出:

array(7) {
  [0]=>
  array(3) {
    ["Product"]=>
    string(21) "Retractor Color: Blue"
    ["Color"]=>
    string(4) "Blue"
    ["Size"]=>
    NULL
  }
  [1]=>
  array(3) {
    ["Product"]=>
    string(58) "Robin Jacket Color: Black (Body) &amp; Red (Stripe)Size: L"
    ["Color"]=>
    string(9) "Black,Red"
    ["Size"]=>
    string(1) "L"
  }
  [2]=>
  array(3) {
    ["Product"]=>
    string(22) "Ladies Clutch in Green"
    ["Color"]=>
    string(5) "Green"
    ["Size"]=>
    NULL
  }
  [3]=>
  array(3) {
    ["Product"]=>
    string(28) "T-Shirt  Color: BlackSize: L"
    ["Color"]=>
    string(5) "Black"
    ["Size"]=>
    string(1) "L"
  }
  [4]=>
  array(3) {
    ["Product"]=>
    string(63) "Full Sleeve Sweat Shirt Color: Grey Melange (Light Grey)Size: S"
    ["Color"]=>
    string(12) "Grey Melange"
    ["Size"]=>
    string(1) "S"
  }
  [5]=>
  array(3) {
    ["Product"]=>
    string(28) "T-Shirt  Color: BlackSize: L"
    ["Color"]=>
    string(5) "Black"
    ["Size"]=>
    string(1) "L"
  }
  [6]=>
  array(3) {
    ["Product"]=>
    string(21) "Speed Jacket  Size: M"
    ["Color"]=>
    NULL
    ["Size"]=>
    string(1) "M"
  }
}