Bacchus
Bacchus

Reputation: 515

Space removed by preg_split

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

Answers (3)

The fourth bird
The fourth bird

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

Regex demo

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

Andreas
Andreas

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."
  }
}

https://3v4l.org/ZFV9t

Upvotes: 2

Kamlesh Solanki
Kamlesh Solanki

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

Related Questions