-1

I'm trying to split a string at question marks, exclamation marks, or periods, but at the same time I'm trying to keep the punctuation marks after splitting them. How would I do that? Thanks.

$input = "Sentence1?Sentence2.Sentence3!";
$input = preg_split("/(\?|\.|!)/", $input);
echo $input[0]."<br>";
echo $input[1]."<br>";
echo $input[2]."<br>";

Desired outputs:

Sentence1?
Sentence2.
Sentence3!

Actual outputs:

Sentence1
Sentence2
Sentence3

jessica
  • 1,667
  • 1
  • 17
  • 35

2 Answers2

1

the manual knows all

PREG_SPLIT_DELIM_CAPTURE If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

so in your case:

$input = preg_split("/(\?|\.|!)/", $input,NULL,PREG_SPLIT_DELIM_CAPTURE);
  • @PaulCrovella I think you're right. When I tested it, an undefined offset error came up, and it only split between sentence1 and sentence2. – jessica Aug 31 '15 at 23:44
1

You can do this by changing the capture group in your regex into a lookbehind like so:

$input = preg_split("/(?<=\?|\.|!)/", $input);
user3942918
  • 25,539
  • 11
  • 55
  • 67