用逗号分隔后跟小写字母

问题描述 投票:2回答:1

请帮我模式。我有逗号的字符串,如:

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

我需要用逗号分割它并得到:

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

如果在逗号分割str之后有小写字母,如何使用规则?

我正在使用[\ s,] [] [A-Z0-9] +,但它修剪了一些文字

php regex preg-replace regex-lookarounds negative-lookahead
1个回答
2
投票

您可以使用基于前瞻的解决方案

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

regex demo

细节

  • \s* - 0+空格
  • , - 一个逗号
  • (?!\s*\p{Ll}) - 如果在当前位置的右边立即有0+空格(\s*),后面跟着一个Unicode小写字母(\p{Ll}),那么这个匹配失败的负面前瞻
  • \s* - 0+空格。

PHP demo

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

输出:

Array
(
    [0] => 12v some
    [1] => Item, which contains comma
    [2] => Another item
)
© www.soinside.com 2019 - 2024. All rights reserved.