使用preg_split拆分字符串

时间:2015-10-18 17:58:43

标签: php regex preg-split

我尝试使用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.

1 个答案:

答案 0 :(得分:4)

使用此正则表达式:

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

Regex live here.

解释

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

希望它有所帮助。