在问号、感叹号或句号处拆分字符串

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

我正在尝试使用 preg_split 在问号、感叹号或句号处拆分字符串,但我 运行 遇到了问题。它不是在问号处拆分,而是在此之前拆分字符串。请看看我的代码:

<?php

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

?>

预期结果:

Why will I have no money

实际结果:

Why will

您需要转义特殊的正则表达式字符(.?)并删除空格。

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

演示:https://eval.in/422337

输出:

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

Regex101 演示:https://regex101.com/r/zK7cK7/1