4

I'm trying to split a string at a question mark, an exclamation mark, or a period using preg_split, but I've ran into a problem. Instead of splitting at the question mark, it split the string way before that. Please take a look at my code:

<?php

    $input = "Why will I have no money? Because I spent it all";
    $input = preg_split( "/ (?|.|!) /", $input ); 
    $input = $input[0];
    echo $input;

?>

Expected results:

Why will I have no money

Actual results:

Why will

chris85
  • 23,846
  • 7
  • 34
  • 51
jessica
  • 1,667
  • 1
  • 17
  • 35

1 Answers1

6

You need to escape the special regex characters (. and ?) and remove the spaces.

<?php
$input = "Why will I have no money? Because I spent it all";
    $input = preg_split( "/(\?|\.|!)/", $input ); 
print_r($input);

Demo: https://eval.in/422337

Output:

Array
(
    [0] => Why will I have no money
    [1] =>  Because I spent it all
)

Regex101 demo: https://regex101.com/r/zK7cK7/1

chris85
  • 23,846
  • 7
  • 34
  • 51