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

前端 未结 2 1379
孤独总比滥情好
孤独总比滥情好 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:24

    No use for PREG_SPLIT_DELIM_CAPTURE if you use a positive lookbehind in your pattern. The function will keep the delimiters.

    $text = preg_split('/(?<=[.:!?])/', 'good:news.everyone!', 0, PREG_SPLIT_NO_EMPTY);
    

    If you use lookbehind, it will just look for the character without matching it. So, in the case of preg_split(), the function will not discard the character.

    The result without PREG_SPLIT_NO_EMPTY flag:

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

    The result with PREG_SPLIT_NO_EMPTY flag:

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

    You can test it using this PHP Online Function Tester.

提交回复
热议问题