正则表达式的分割已经被之前的答案很好地演示了,但我认为这是一个完美的情况,可以调用ctype_space()
来确定哪个结果数组应该接收遇到的值。
代码:(演示)
$string = "This is a string";
$words = [];
$spaces = [];
foreach (preg_split('~( +)~', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $s) {
if (ctype_space($s)) {
$spaces[] = strlen($s);
} else {
$words[] = $s;
}
}
var_export([
'words' => $words,
'spaces' => $spaces
]);
输出:
array (
'words' =>
array (
0 => 'This',
1 => 'is',
2 => 'a',
3 => 'string',
),
'spaces' =>
array (
0 => 1,
1 => 1,
2 => 4,
),
)
如果你想替换 preg_split()
中使用的管道常量,你可以直接使用 3
(演示)。这代表了 PREG_SPLIT_NO_EMPTY
,它是 1
加上 PREG_SPLIT_DELIM_CAPTURE
,它是 2
。请注意,虽然代码宽度减小了,但你也会失去代码可读性。
preg_split('~( +)~', $string, -1, 3)
' ' (1), ' ' (1), ' ' (4)
。 - silkfire