在某些字符之间加上一个

时间:2013-05-29 16:23:39

标签: php regex

我有一个遵循这个可预测模式的字符串:

This is a string, it has a comma in it, This is another string, it also has a comma in it, This is a third string, it follows the trend

等等。

显然字符串表示一个列表,用逗号分隔。只是,列表的项目也包含逗号。确定新项目开头的方法是大写字母。

我设法将模式与此匹配:[, \p{Lu}]但我不确定接下来该做什么。如果我使用preg_split()我会丢失逗号,这是所希望的,但我也丢失了大写字母,而不是。正确的preg_replaced字符串应如下所示

This is a string, it has a comma in it<br />
This is another string, it also has a comma in it<br />
This is a third string, it follows the trend

1 个答案:

答案 0 :(得分:11)

使用lookahead assertion

$result = preg_replace('/, (?=\p{Lu})/u', '<br />\n', $subject);

正则表达式的意思是“匹配,和空格,但前提是它们后跟一个大写的Unicode字母”。这样,这封信就不会成为比赛本身的一部分。