Skip to content

Instantly share code, notes, and snippets.

@keinajar
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keinajar/37e2dbf32e486cc84873 to your computer and use it in GitHub Desktop.
Save keinajar/37e2dbf32e486cc84873 to your computer and use it in GitHub Desktop.
Split a string by string (like explode()) backwards. See http://stackoverflow.com/q/16610791/216129
<?php
/**
* Split a string by string (like explode()) backwards.
*
* @param string $delimiter <p>The boundary string</p>
* @param string $string <p>The input string</p>
* @param int $limit <p>
* If limit is set and positive, the returned array will contain
* a maximum of limit elements counting from the end of the string with the first
* element containing the rest of string (from the beginning).
* </p>
* <p>
* If the limit parameter is negative, all components
* except the first -limit are returned.
* </p>
* <p>
* If the limit parameter is zero, then this is treated as 1.
* </p>
* @param bool $keep_order If true, array elements are in the same order as they appear in the text; if false the order is reversed
* @return array If delimiter is an empty string (""),
* explode will return false.
* If delimiter contains a value that is not
* contained in string and a negative
* limit is used, then an empty array will be
* returned. For any other limit, an array containing
* string will be returned.
* @see explode()
*/
function backward_explode($delimiter, $string, $limit = null, $keep_order = true) {
if ((string)$delimiter === "") {
return false;
}
if ($limit === 0 || $limit === 1) {
return array($string);
}
$explode = explode($delimiter, $string);
if ($limit === null || $limit === count($explode)) {
return $keep_order? $explode : array_reverse($explode);
}
$parts = array();
if ($limit > 0) {
for ($i = 1; $i < $limit; $i++) {
$parts[] = array_pop($explode);
}
$remainder = implode($delimiter, $explode);
$parts[] = $remainder;
if ($keep_order) {
$parts = array_reverse($parts);
}
} else {
if (strpos($string, $delimiter) === false) {
return array();
}
$parts = $explode;
array_splice($parts, 0, abs($limit));
if (!$keep_order) {
$parts = array_reverse($parts);
}
}
return $parts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment