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?
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.
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.
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.
The str_split() function splits a string into an array.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With