Ordered string to array PHP

27 Views Asked by At

I have a problem with converting the string:

$str = "1. List of word synonyms 2) Glass plastic products 3. Other product";

into an array list:

Array(
  [0] => List of word synonyms
  [1] => Glass plastic products
  [2] => Other product
)

I tried using preg_replace, but I can't come up with a pattern that would be able to do it.

1

There are 1 best solutions below

0
jahantaila On BEST ANSWER

You can use preg_split() to split the string into an array based on a regular expression pattern. In this case, you can split on any number followed by a period and a space. Here's an example code snippet:

$str = "1. List of word synonyms 2) Glass plastic products 3. Other product";
$array = preg_split('/\d+\.\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($array);

And this will output the following:

Array
(
    [0] => List of word synonyms
    [1] => Glass plastic products
    [2] => Other product
)