Split with comma not followed with a lowercase letter

Viewed 71

Help me with pattern please. I have string with commas like:

12v some, Item, which contains comma, Another item

I need to split it by commas and get:

 0 => '12v some'
 1 => 'Item, which contains comma'
 2 => 'Another item'

how to use rule if there are letter in lowercase after comma dont split str?

I'm using [\s,][ ][A-Z0-9]+, but it trim some text

1 Answers

You may use a lookahead based solution like

preg_split('~\s*,(?!\s*\p{Ll})\s*~', $s)

See the regex demo

Details

  • \s* - 0+ whitespaces
  • , - a comma
  • (?!\s*\p{Ll}) - a negative lookahead that fails the match if, immediately to the right of the current location, there are 0+ whitespaces (\s*) followed with a Unicode lowercase letter (\p{Ll})
  • \s* - 0+ whitespaces.

PHP demo:

$s = "12v some, Item, which contains comma, Another item";
$res = preg_split('~\s*,(?!\s*\p{Ll})\s*~', $s);
print_r($res);

Output:

Array
(
    [0] => 12v some
    [1] => Item, which contains comma
    [2] => Another item
)
Related