From the form comes the data that must be parsed regular. The result is an array of the form

Array ( [0] => Array ( [0] => Зачаровать Оружие [12] F [1] => Зачаровать Оружие [2] => 12 [3] => [4] => F ) [1] => Array ( [0] => Зачаровать Оружие [12] F [1] => Зачаровать Оружие [2] => 12 [3] => [4] => F ) 

I need to receive an array of a type

 Array ( [Зачаровать Оружие] => Array ( [0] => Зачаровать Оружие [11] (x2) VP [1] => Зачаровать Оружие [2] => 11 [3] => 2 [4] => VP ) [Зачаровать Обувь] => Array ( [0] => Зачаровать Обувь [11] VP [1] => Зачаровать Обувь [2] => 11 [3] => [4] => VP ) [Зачаровать Поножи] => Array ( [0] => Зачаровать Поножи [11] VP [1] => Зачаровать Поножи [2] => 11 [3] => [4] => VP ) 

In other words, so that each category of things contains a subcategory of things that belongs to the main category. I implemented some kind of option, but I got a lot of duplicate code, tell me how you can implement it easier.

 function parseInfo($data,$category) { $matches = array(); switch($category){ case "charki" : $pattern = "/(Зачаровать\s\D{1,8})\s\[(\d{1,2})\].{1,3}?(\d{1,2})?.{1,3}?([PVFERUL]+)/u";break; } preg_match_all($pattern,$data,$found,PREG_SET_ORDER); foreach($found as $item){ $itemCat = $item[1]; $thing = $item[1]." ".$item[2]." ".$item[4]; if(isset($matches[$itemCat])){ if(isset($matches[$itemCat][$thing])){ }else{ $matches[$itemCat][$thing] = $item; } }else{ if(isset($matches[$itemCat][$thing])){ }else{ $matches[$itemCat][$thing] = $item; } } } return $matches; } 
  • Please give an example of the incoming line (or lines) to be able to check your regular season. - terantul
  • Enchant Shoes [11] F (Weight: 0.1) Expand / CollapseLongevity: 0/1 Minimum Required: • Level: 11 Acts on: • Stitching Protection: +2 • Slitting Damage Protection: +4 • Criting Damage Protection: +2 Enchant Leggings [11] F (Mass: 0.1) Expand / CollapseDurability: 0/1 Minimum Required: • Level: 11 Acts on: • Matt. against dodge (%): +4 • Protection against magic: +1 • Protection against magic of fire: +2 • Protection against splitting damage: +2 • Protection against crushing damage: +1 • Protection against cutting damage: +1 • Protection against water magic: +1 - quaresma89

2 answers 2

How would I do it (without correcting the regulars):

 function parseInfo($data, $category) { $matches = array(); $found = array(); switch ($category) { case "charki": $pattern_parts = array( # Выбрать 1-8 НЕ цифр. Назначить рез-ту ключ "item". 'item' => '(?<item>\D{1,8})', # Внутри "[]" выбрать 1-2 цифры. Назначить рез-ту ключ "category". 'category' => '\[(?<category>\d{1,2})\]', # Не группировать содержимое "()". # Найти внутри "()" букву "x" и выбрать после нее 1-2 цифры. # Назначить рез-ту ключ "x". 'multiplier' => '(?:\(x(?<x>\d{1,2})\))?', # Найти одну букву из списка "PVFERUL". Назначить рез-ту ключ "mode". 'mode' => '(?<mode>[PVFERUL]+)' ); # Склеиваем части паттерна, вставляя между значениями \s* $pattern = '@Зачаровать' . join('\s*', $pattern_parts) . ' @u '; break; } preg_match($pattern, $data, $found); foreach ($found as $k => $v) { # Интересуют только заданные нами именованные ключи if (!is_int($k)) { # Если 'multiplier' пуст - присваиваем ему 1 # Все ключи обрабатываем функцией 'trim' $matches[$k] = ($k === 'multiplier' && empty($v)) ? 1 : trim($v); } } return $matches; } 

Tests:

 $db = array(); $text = 'Зачаровать Обувь [11] F (Масса: 0.1) Развернуть/свернутьДолговечность: 0/1 Требуется минимальное: Уровень: 11 Действует на: Защита от колющего урона: +2 Защита от рубящего урона: +4 Защита от дробящего урона: +2 Зачаровать Поножи [11] F (Масса: 0.1) Развернуть/свернутьДолговечность: 0/1 Требуется минимальное: Уровень: 11 Действует на: Мф. против увертывания (%): +4 Защита от магии: +1 Защита от магии огня: +2 Защита от колющего урона: +2 Защита от дробящего урона: +1 Защита от режущего урона: +1 Защита от магии воды: +1'; $lines = explode(PHP_EOL, $text); foreach ($lines as $line) { $temp = parseInfo($line, $category = "charki"); if (!empty($temp)) { $db[] = $temp; } } echo "<pre>"; print_r($db); echo "</pre>"; 

 Array ( [0] => Array ( [item] => Обувь [category] => 11 [multiplier] => 1 [mode] => F ) [1] => Array ( [item] => Поножи [category] => 11 [multiplier] => 1 [mode] => F ) ) 
  • While writing the answer, the conditions have changed. In the process of correction ... - VenZell
  • An example is very interesting, just please explain why the regular schedule is divided into parts, what does this give us as a result? - quaresma89
  • To increase readability. Compare: @ Enchant (? P <item> \ D {1,8}) \ s * [(? P <category> \ d {1,2})] \ s * (? :( x (? P <multiplier > \ d {1,2})))? \ s * (? P <mode> [PVFERUL] +) @ u - VenZell
  • + You assign names to indices right away, this is very convenient, since I had to go over the array and assign names again, it was very inconvenient! - quaresma89
  • I figured out your code and what is what, but it doesn’t solve the problem itself - quaresma89

I decided this way. If you can easily and efficiently ask

 public $patternParts = array( 'category' => '/(?<category>Зачаровать\s\D{1,8})', 'level' => '\[(?<level>\d{1,2})\]', 'quantity' => '(?:\(x(?<quantity>\d{1,2})\))?', 'quality' => '(?<quality>[PVFERUL]+)/u' ); function parseInfo($dataForm){ $matches = array(); $pattern = join("\s*",$this->patternParts); preg_match_all($pattern,$dataForm,$found,PREG_SET_ORDER); foreach($found as $item){ if($item['quantity'] == ""){ $item['quantity'] = 1; } $thing = trim($item['category']." ".$item['level']." ".$item['quality']); $category = trim($item['category']); if(!isset($matches[$category][$thing])){ $matches[$category][$thing] = $item; }else{ $matches[$category][$thing]['quantity'] += $item['quantity']; } } return $matches; } 

Result

  [Зачаровать Кольцо] => Array ( [Зачаровать Кольцо 11 P] => Array ( [0] => Зачаровать Кольцо [11] P [category] => Зачаровать Кольцо [1] => Зачаровать Кольцо [level] => 11 [2] => 11 [quantity] => 2 [3] => [quality] => P [4] => P ) [Зачаровать Кольцо 12 VP] => Array ( [0] => Зачаровать Кольцо [12] (x7) VP [category] => Зачаровать Кольцо [1] => Зачаровать Кольцо [level] => 12 [2] => 12 [quantity] => 7 [3] => 7 [quality] => VP [4] => VP ) ) 
  • True, the keys are not unnecessary rejected, but I will correct it. Interests the opinion of the method itself. - quaresma89