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.