在使用 preg_split 后保留标点符号?
Keeping the punctuation marks after using preg_split at?
我试图在问号、感叹号或句号处拆分字符串,但同时我试图在拆分后保留标点符号。我该怎么做?谢谢
$input = "Sentence1?Sentence2.Sentence3!";
$input = preg_split("/(\?|\.|!)/", $input);
echo $input[0]."<br>";
echo $input[1]."<br>";
echo $input[2]."<br>";
期望输出:
句子 1?
Sentence2.
Sentence3!
实际输出:
句子 1
句子2
Sentence3
manual无所不知
PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
所以在你的情况下:
$input = preg_split("/(\?|\.|!)/", $input,NULL,PREG_SPLIT_DELIM_CAPTURE);
您可以通过将正则表达式中的捕获组更改为 lookbehind 来实现,如下所示:
$input = preg_split("/(?<=\?|\.|!)/", $input);
我试图在问号、感叹号或句号处拆分字符串,但同时我试图在拆分后保留标点符号。我该怎么做?谢谢
$input = "Sentence1?Sentence2.Sentence3!";
$input = preg_split("/(\?|\.|!)/", $input);
echo $input[0]."<br>";
echo $input[1]."<br>";
echo $input[2]."<br>";
期望输出:
句子 1?
Sentence2.
Sentence3!
实际输出:
句子 1
句子2
Sentence3
manual无所不知
PREG_SPLIT_DELIM_CAPTURE If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
所以在你的情况下:
$input = preg_split("/(\?|\.|!)/", $input,NULL,PREG_SPLIT_DELIM_CAPTURE);
您可以通过将正则表达式中的捕获组更改为 lookbehind 来实现,如下所示:
$input = preg_split("/(?<=\?|\.|!)/", $input);