RLL
RLL

Reputation: 71

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!

Upvotes: 4

Views: 131

Answers (2)

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

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

Use this regex:

name:\s(.*),\slocation:\s(.*),\sdescription:\s(.*),\sskills:\s(.*)

$text = 'name: jo mamma, location: Atlanta, Georgia, description: He is a good boy, and he is pretty funny, skills: not much at all!';
preg_match_all('/name:\s(.*),\slocation:\s(.*),\sdescription:\s(.*),\sskills:\s(.*)/', $text, $text_matches); 

for ($index = 1; $index < count($text_matches); $index++) {
    echo $text_matches[$index][0].'<br />';
}

Output:

jo mamma
Atlanta, Georgia
He is a good boy, and he is pretty funny
not much at all!

Regex101

Upvotes: 2

Related Questions