在标点符号上拆分字符串而不丢失符号[重复]

问题描述 投票:0回答:1

我正在尝试使用 preg_split 拆分字符串,但我想包含分隔符,并且我不想捕获空字符串。我该怎么做?

$inputX = "hello1.hello2.";
$tempInput = preg_split( "~(\?|\.|!|\,)~", $inputX); //split the input at .!?,
print_r($tempInput)

结果:

Array ( [0] => hello1 [1] => hello2 [2] => )

需要结果:

Array ( [0] => hello1. [1] => hello2.
php regex preg-split
1个回答
4
投票

使用这个正则表达式:

(?<=[.!?])(?!$|[.!?])

正则表达式就在这里。

解释:

(?<=          # looks for positions after
    [.!?]     # one of these three characters
)             #
(?!           # but not
    $         # at the end
    |         # OR
    [.!?]     # before one of these three characters
 )            #

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.