tags:

views:

85

answers:

3

For example, I have an article should be splitted according to sentence boundary such as ".", "?", "!" and ":".

But as well all know, whether preg_split or explode function, they both remove the delimiter.

Any help would be really appreciated!

EDIT:

I can only come up with the code below, it works great though.

$content=preg_replace('/([\.\?\!\:])/',"\\1[D]",$content);

Thank you!!! Everyone. It is only five minutes for getting 3 answers! And I must apologize for not being able to see the PHP manual carefully before asking question. Sorry.

A: 

preg_split, read it better

Col. Shrapnel
+2  A: 

You can set the flag PREG_SPLIT_DELIM_CAPTURE when using preg_split and capture the delimiters too. Then you can take each pair of 2‍n and 2‍n+1 and put them back together:

$parts = preg_split('/([.?!:])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();
for ($i=0, $n=count($parts)-1; $i<$n; $i+=2) {
    $sentences[] = $parts[$i].$parts[$i+1];
}
if ($parts[$n] != '') {
    $sentences[] = $parts[$n];
}

Note to pack the splitting delimiter into a group, otherwise they won’t be captured.

Gumbo
+1  A: 

preg_split with PREG_SPLIT_DELIM_CAPTURE flag

Will return matches array with 0=delimiter, 1=match

Shaun Hare