PHP preg_split为新行添加拆分

时间:2018-12-12 20:25:55

标签: php regex preg-split

我正在使用此preg_split来分割法线,只要后面有空格或大写字母的点都可以。

$p = "This is a dummy text. And it has a new line in it \n it also has dots. Byt not";
$arr  = preg_split('/\.\s*?(?=[A-Z])/', $p);

这也可以防止段落中的最后一个点被分割(这是我想要的),但是,我现在也需要它来分割新行(或行)。我无法把头缠住...:(

2 个答案:

答案 0 :(得分:1)

尝试一下:

$arr  = preg_split('/\.\s*?(?=[A-Z])|(\r\n|\n|\r)/', $p);

答案 1 :(得分:1)

您可以使用以下一种替换方式来进行拆分:匹配一个点,然后匹配0+个水平空白字符,然后匹配1+个大写字符或| Unicode换行符序列:

\.(?=\h*[A-Z])|\R+

例如:

$p = "This is a dummy text. And it has a new line in it \n it also has dots. Byt not.";
$arr  = preg_split('/\.(?=\h*[A-Z])|\R+/', $p);

请参见Regex demo | php demo