Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string at question mark, exclamation mark, or period

Tags:

php

preg-split

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

like image 948
jessica Avatar asked Aug 31 '25 16:08

jessica


1 Answers

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

like image 171
chris85 Avatar answered Sep 02 '25 04:09

chris85