Exploding a string, only at the last occurrence of the explode match

Viewed 3513

I'm trying to explode a string, but I need it to explode only at the last 'and' instead of every 'and'. Is there a way to do that?

<?php

$string = "one and two and three and four and five";
$string = explode(" and ", $string);

print_r($string);

?>

Result:

Array ( [0] => one [1] => two [2] => three [3] => four [4] => five )

Need Result:

Array ( [0] => one and two and three and four [1] => five )

6 Answers

You can also use preg_split:

Single-character delimiter

$string = "one,two,three,four,five";
$delimiter = ",";

// The regexp will look like this:  /,([^,]+)$/   
$array = preg_split("/".$delimiter."([^".$delimiter."]+)$/", $string,
  -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

print_r($array);

The regular expression matches the last delimiter with the last item, but captures only the item so that it's kept in the results thanks to PREG_SPLIT_DELIM_CAPTURE.

PREG_SPLIT_NO_EMPTY is there because, I'm not sure why, the split gives an empty string at the end.

Multi-character delimiter

The regular expression has to be adapted here, using a negative look-around (as explained in this answer):

$string = "one and two and three and four and five";
$delimiter = " and ";

$array = preg_split("/$delimiter((?(?!$delimiter).)*$)/", $string,
  -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

print_r($array);

(?(?!$delimiter).)* means: match only characters that do no start the word $delimiter. The first ? prevents capturing an additional group.

Related