Search code examples
phpregexpreg-matchpreg-match-all

preg_match_all separated by commas with values probably containing spaces


I currently have a preg_match_all being used on regular strings that contain no spaces but I now need to make it work for anything between each space.

I need abc, hh, hey there, 1 2 3, hey_there_ to return abc hh hey there``1 2 3 hey_there_

But my current script just stops when a space is involved.

preg_match_all("/([a-zA-Z0-9_-]+)+[,]/",$threadpolloptions,$polloptions);
foreach(array_unique($polloptions[1]) as $option) {
     $test .= $option.' > ';
}

Solution

  • You dont need regular expresion in this case. Explode will be faster

    $str = 'abc, hh, hey there, 1 2 3, hey_there_';
    print_r(explode(', ', $str));
    

    result

    Array
    (
        [0] => abc
        [1] => hh
        [2] => hey there
        [3] => 1 2 3
        [4] => hey_there_
    )
    

    UPDATE

    $str = 'abc, hh,hey there, 1 2 3, hey_there_';
    print_r(preg_split("/,\s*/", $str));
    

    result the same