Search code examples
phpexplodepreg-split

Splitting a single string to an array on more than one delimiter


Is it possible to explode the following:

08 1.2/3(1(1)2.1-1

to an array of {08, 1, 2, 3, 1, 1, 2, 1, 1}?

I tried using preg_split("/ (\s|\.|\-|\(|\)) /g", '08 1.2/3(1(1)2.1-1') but it returned nothing. I tried checking my regex here and it matched well. What am I missing here?


Solution

  • You should use a character class containing all the delimiters which you want to use for splitting. Regex character classes appear inside [...]:

    <?php
    $keywords = preg_split("/[\s,\/().-]+/", '08 1.2/3(1(1)2.1-1');
    print_r($keywords);
    

    Result:

    Array ( [0] => 08 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 1 [6] => 2 [7] => 1 [8] => 1 )