<?php
$text = "Testing text splitting\nWith a newline!";
$textArray = preg_split('/\s+/', $text, 0, PREG_SPLIT_DELIM_CAPTURE);
print_r($textArray);
以上代码将输出以下内容:
Array
(
[0] => Testing
[1] => text
[2] => splitting
[3] => With
[4] => a
[5] => newline!
)
但据我所知,PREG_SPLIT_DELIM_CAPTURE标志应该捕获数组中的空白分隔符。我错过了什么吗?
编辑:好的,重新阅读文档后,我现在明白PREG_SPLIT_DELIM_CAPTURE并不适用于这种情况。我想要的输出是这样的:
Array
(
[0] => Testing
[1] => ' '
[2] => text
[3] => ' '
[4] => splitting
[5] => '\n'
[6] => With
[7] => ' '
[8] => a
[9] => ' '
[10] => newline!
)
答案 0 :(得分:0)
因此,如果您再次阅读PREG_SPLIT_DELIM_CAPTURE
手册,请说明:
如果设置了此标志,则将捕获并返回分隔符模式中的带括号的表达式。
你会突然明白expression in the delimiter pattern
(在你的情况下是\s
)只有在captured
时才会parentheses
(即加到结果中)。现在,您可以:
$text = "Testing text splitting\nWith a newline!";
$textArray = preg_split('/(\s+)/', $text, 0, PREG_SPLIT_DELIM_CAPTURE);
// parentheses!
print_r($textArray);
答案 1 :(得分:0)
您也可以使用T-Regx library:
$textArray = pattern('(\s+)')->split("Testing text splitting\nWith a newline!")->inc();