How do I include the split delimiter in results for preg_split()?

前端 未结 2 1377
孤独总比滥情好
孤独总比滥情好 2020-11-30 07:41

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

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

But I want to include . :

2条回答
  •  佛祖请我去吃肉
    2020-11-30 08:07

    Here you go:

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

    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 => '',
    );
    

    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!'
    );
    

提交回复
热议问题