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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With