Retain Delimiters when Splitting String
Posted
by JoeC
on Stack Overflow
See other posts from Stack Overflow
or by JoeC
Published on 2010-05-20T17:40:20Z
Indexed on
2010/05/20
17:50 UTC
Read the original article
Hit count: 214
Edit: OK, I can't read, thanks to Col. Shrapnel for the help. If anyone comes here looking for the same thing to be answered...
print_r(preg_split('/([\!|\?|\.|\!\?])/', $string, null, PREG_SPLIT_DELIM_CAPTURE));
Is there any way to split a string on a set of delimiters, and retain the position and character(s) of the delimiter after the split?
For example, using delimiters of !
?
.
!?
turning this:
$string = 'Hello. A question? How strange! Maybe even surreal!? Who knows.';
into this
array('Hello', '.', 'A question', '?', 'How strange', '!', 'Maybe even surreal', '!?', 'Who knows', '.');
Currently I'm trying to use print_r(preg_split('/([\!|\?|\.|\!\?])/', $string));
to capture the delimiters as a subpattern, but I'm not having much luck.
© Stack Overflow or respective owner