Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ordered string to array PHP

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading