如何在preg_split()的结果中包括分割定界符? [英] How do I include the split delimiter in results for preg_split()?

查看:80
本文介绍了如何在preg_split()的结果中包括分割定界符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模式,可以将文本分成句点:

I have this simple pattern that splits a text into periods:

$text = preg_split("/[\.:!\?]+/", $text);

但是我想在数组项的末尾包含. :!.

But I want to include . : or ! at the end of the array items.

也就是说,现在是"good:news.everyone!".我有:

That is, now for "good:news.everyone!" I have:

array("good", "news", "everyone", "");

但是我想要

array("good:", "news.", "everyone!", "");

推荐答案

在这里:

preg_split('/([^.:!?]+[.:!?]+)/', 'good:news.everyone!', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

它是如何工作的:模式实际上将所有内容都变成了定界符.然后,要将这些定界符包括在数组中,可以使用PREG_SPLIT_DELIM_CAPTURE常量.这将返回一个数组,如:

How it works: The pattern actually turns everything into a delimiter. Then, to include these delimiters in the array, you can use the PREG_SPLIT_DELIM_CAPTURE constant. This will return an array like:

array (
    0 => '',
    1 => 'good:',
    2 => '',
    3 => 'news.',
    4 => '',
    5 => 'everyone!',
    6 => '',
);

要摆脱空值,请使用PREG_SPLIT_NO_EMPTY.要组合两个或多个这些常量,我们使用按位|运算符.结果:

To get rid of the empty values, use PREG_SPLIT_NO_EMPTY. To combine two or more of these constants, we use the bitwise | operator. The result:

array (
    0 => 'good:',
    1 => 'news.',
    2 => 'everyone!'
);

这篇关于如何在preg_split()的结果中包括分割定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆