Search code examples
phpregexsplitpreg-split

Split a string on commas which are followed by a space, word, then a colon


I am working with an API and getting results via an API. I am having trouble with the delimitation to split the array. Below is the sample example data I am receiving from the API:

name: jo mamma, location: Atlanta, Georgia, description: He is a good boy, and he is pretty funny, skills: not much at all!

I would like to be able to split like so:

name: jo mamma

location: Atlanta, Georgia

description: He is a good boy, and he is pretty funny

skills: not much at all!

I have tried using the explode function and the regex preg_split.

$exploded = explode(",", $data);
$regex = preg_split("/,\s/", $data);

But not getting the intended results because its splitting also after boy, and after Georgia. Results below:

name: jo mamma

location: Atlanta

Georgia

description: He is a good boy

and he is pretty funny

skills: not much at all!


Solution

  • Just do this simple split using Zero-Width Positive Lookahead . (It will split by only , after which there is text like name:).

    $regex = preg_split("/,\s*(?=\w+\:)/", $data);
    /*
    Array
        (
           [0] => "name: jo mamma"
           [1] => "location: Atlanta, Georgia"
           [2] => "description: He is a good boy, and he is pretty funny"
           [3] => "skills: not much at all!"
        )
     */ 
    

    Learn more on lookahead and lookbehind from here : http://www.regular-expressions.info/lookaround.html