-2

I need to split or explode a string.

K1123-Food, Apple, Z3456-Egg, Mushroom, M9902-Plant, Soil, Water, Q8876-Medicine, Car, Splitter

into something like

K1123-Food, Apple
Z3456-Egg, Mushroom
M9902-Plant, Soil, Water
Q8876-Medicine, Car, Splitter

Ideas on how to apply preg_split or explode will be welcomed.

Thanks in advance.

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
davykiash
  • 1,796
  • 5
  • 27
  • 60

1 Answers1

1

Here is a solution for you, using preg_match_all():

$s = 'K1123-Food, Apple, Z3456-Egg, Mushroom, M9902-Plant, Soil, Water, Q8876-Medicine, Car, Splitter';
$pattern = '/(\w\d+-\w+(, [^\d]*))(, |$)/';
$matches = [];

preg_match_all($pattern, $s, $matches);

print_r($matches[1]);

This outputs

Array
(
    [0] => K1123-Food, Apple
    [1] => Z3456-Egg, Mushroom
    [2] => M9902-Plant, Soil, Water
    [3] => Q8876-Medicine, Car, Splitter
)

OK so this is an advanced solution that tries to capture content mentioned by Toto:

$s = 'K1123-Food, Apple2, 123-456, Mushroom, Z3456-Egg, Mushroom, M9902-Plant, Soil, Water, Q8876-Medicine, Car, Splitter';
$pattern = '/([A-Z]\d+-\w+(.(?!([A-Z]\d))+)+)(, |$)/';
$matches = [];

preg_match_all($pattern, $s, $matches);
print_r($matches[1]);

which outputs

Array
(
    [0] => K1123-Food, Apple2, 123-456, Mushroom
    [1] => Z3456-Egg, Mushroom
    [2] => M9902-Plant, Soil, Water
    [3] => Q8876-Medicine, Car, Splitter
)

Keep in mind that it will never be possible to automatically and correctly put structure into otherwise unstructured content. Every possible solution will make some assumptions about how your data really need to be structured.

T Grando
  • 168
  • 4