我想用点和空格分隔字符串。但是,preg_split
会从匹配的部分删除空格。
如何保留空间?
preg_split('/(?<=[.])\s+/u', 'One. Two. Three.', null, PREG_SPLIT_NO_EMPTY);
// Result: ['One.', 'Two.', 'Three.']
// Expected: ['One. ', 'Two. ', 'Three.']
答案 0 :(得分:2)
您可以将正向搜索转换为匹配项,然后使用\K
来忘记匹配的项。另外,要匹配一个或多个空格,请使用\s+
。
\.\s+\K
var_dump(preg_split('/\.\s+\K/', 'One. Two. Three.', null, PREG_SPLIT_NO_EMPTY));
结果
array(3) {
[0]=>
string(5) "One. "
[1]=>
string(5) "Two. "
[2]=>
string(6) "Three."
}
答案 1 :(得分:2)
您可以使用preg_match_all并匹配点和空格(可选)
preg_match_all("/(.*?\.\s*)/", 'One. Two. Three.',$m);
结果:
array(2) {
[0]=>
array(3) {
[0]=>
string(5) "One. "
[1]=>
string(5) "Two. "
[2]=>
string(6) "Three."
}
[1]=>
array(3) {
[0]=>
string(5) "One. "
[1]=>
string(5) "Two. "
[2]=>
string(6) "Three."
}
}
答案 2 :(得分:0)
根据您的预期结果。
$string = 'One. Two. Three.';
$split = preg_split("/(\w+\W+)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
var_dump($split);