Reputation: 515
I want to split the string by a dot followed by a space. However, preg_split
removes the space from the matched part.
How can I keep the space?
preg_split('/(?<=[.])\s+/u', 'One. Two. Three.', null, PREG_SPLIT_NO_EMPTY);
// Result: ['One.', 'Two.', 'Three.']
// Expected: ['One. ', 'Two. ', 'Three.']
Upvotes: 1
Views: 236
Reputation: 163457
You could turn the positive lookahead into a match and then use \K
to forget what was matched. Also, to match one or more whitespaces, use \s+
.
\.\s+\K
var_dump(preg_split('/\.\s+\K/', 'One. Two. Three.', null, PREG_SPLIT_NO_EMPTY));
Result
array(3) {
[0]=>
string(5) "One. "
[1]=>
string(5) "Two. "
[2]=>
string(6) "Three."
}
Upvotes: 2
Reputation: 23958
You can use preg_match_all and match anything then dot and an optional space
preg_match_all("/(.*?\.\s*)/", 'One. Two. Three.',$m);
Results:
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."
}
}
Upvotes: 2
Reputation: 646
As per your expected result.
$string = 'One. Two. Three.';
$split = preg_split("/(\w+\W+)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
var_dump($split);
Upvotes: 0