Nealv
Nealv

Reputation: 6884

PHP preg_split remove last occurence if it is the end of the string

I have a string that is build like this:

$value = "0::1\n1::4\n2::5\n";

Which I split with a preg_split:

$result = preg_split ('/$\R?^/m', $value);

This gives me an array, the problem is that the last "\n"is not removed. Is there a flag with preg_split to remove this as well?

array:

array(
  0 = "0::1",
  1 = "1::4",
  2 = "2::5\n"
); 

Upvotes: 1

Views: 427

Answers (2)

revo
revo

Reputation: 48751

The other solution could be:

var_dump(array_filter(explode("\n", $value)));

Output:

array(3) {
  [0]=>
  string(4) "0::1"
  [1]=>
  string(4) "1::4"
  [2]=>
  string(4) "2::5"
}

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76636

No, there is no such flag. Use array_map() to remove it:

$result = preg_split ('/$\R?^/m', $value);
$result = array_map('trim', $result);

Upvotes: 1

Related Questions