Separating a comma string while ignoring other commas (not quoted)

I work with the API and get the results through the API. I'm having problems with delimiting to split an array. The following are examples of sample data that I get from the API:

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

I would like to be able to break up like this:

name: jo mamma

Location: Atlanta, Georgia

Description: He is a good boy and he is quite funny.

skills: not so much!

I tried using the explode function and regex preg_split.

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

But do not get the intended results, because his splitting is also after the boy and after Georgia. Results below:

name: jo mamma

Location: Atlanta

Georgia

Description: He is a good boy.

and he's pretty funny

skills: not so much!

. .

+4
2

, Zero-Width Positive Lookahead. ( ,, 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!"
    )
 */ 

lookahead lookbehind : http://www.regular-expressions.info/lookaround.html

+2

:

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 />';
}

:

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

Regex101

+2

Source: https://habr.com/ru/post/1621039/


All Articles