Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string separated by commas and equal sign in php with escaping

Tags:

regex

php

pcre

I want to split a string like this:

colors = blue, green, yellow, kinda violet\, not sure,purple\=almost magenta

With regular expression so the result should be

colors
blue
green
yellow
kinda violet\, not sure
purple\=almost magenta

I've been trying for hours but didn't succeed with ugly constructions like this (for preg_match_all):

/(.*)\s*[=]\s*((.+)\s*,\s*)*/

and this (for preg_split)

/\s*[=,^(\\,)^(\\=)]\s*/

Please, explayne what am I doing wrong?

like image 709
Ilia Andrienko Avatar asked Mar 22 '13 12:03

Ilia Andrienko


People also ask

How to split comma separated string in PHP?

Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.

How to get comma separated values in PHP?

The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.

How can I split a string into two strings in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

How to split a string into array in PHP?

The str_split() function splits a string into an array.


2 Answers

You would need negative lookbehind assertions:

$s = 'colors = blue, green, yellow, kinda violet\, not sure,purple\=almost magenta';

$res = preg_split('/(?<!\\\\)[,=]\s*/', $s);

print_r($res);

Basically it matches a comma (or equal sign) followed by an optional sequence of space characters BUT ONLY if there's no backslash preceding it.

like image 138
Ja͢ck Avatar answered Oct 12 '22 06:10

Ja͢ck


Not very elegant, but this should do the trick with preg_split

/(\s*=\s*)|(\s*,\s*)|(\s*\\=\s*)|(\s*\\,\s*)/g

Most importantly, don't forget the g at the end for global matching.

like image 20
Mustapha Avatar answered Oct 12 '22 04:10

Mustapha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!