Explode only by last delimiter

Explode only by last delimiter

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Explode Only by Last Delimiter

The standard explode() function in PHP operates on a first-come, first-served basis. When you pass a string containing multiple instances of a delimiter to this function, it splits the string at every occurrence, returning an array with as many elements as there are delimiters plus one. This behavior is predictable for parsing CSV data or splitting paths, but it breaks down when your data contains compound values that share a common separator character.

Consider a scenario where you have a string like "one_two_ ... _three_four". Your goal isn't to split every underscore; instead, you want to treat the final underscore as the sole boundary between a complex identifier and a simple suffix. The desired output splits the string into "one_two_three ..." and "four".

To achieve this, you must bypass explode() entirely or wrap its logic in a conditional flow that processes the split results dynamically. Since explode() lacks a parameter to specify "split only at the last occurrence," the solution involves leveraging the function's return value to reconstruct the original segments.

The Reverse-Split Strategy

The most robust approach without using regex is to reverse the problem. You know exactly how many splits you want to make (in this specific case, one). Therefore, you can split the string by the delimiter and then iterate through the resulting array from the end backward. By joining all elements except the last one back together with the delimiter, you effectively isolate the final split point.

Here is a practical implementation:

$string = "one_two_  ... _three_four";
$delimiter = "_";

// Perform the standard explode first
$parts = explode($delimiter, $string);

// Reconstruct the first part by joining all elements except the last
$result = [
    implode($delimiter, array_slice($parts, 0, -1)),
    array_pop($parts)
];

echo $result[0]; // one_two_three ...
echo $result[1]; // four

This method is efficient and readable. It assumes that the delimiter does not appear inside the final segment you want to preserve as a single unit. If your data structure allows for empty segments at the end, array_pop() safely handles them by removing the last element from the temporary array before joining.

Alternative: Regular Expressions with Limiters

While the reverse-slice method is functionally sound, regular expressions offer a more declarative way to express "split until the last delimiter." You can use preg_match_all or preg_split with the appropriate flags. However, standard preg_split() in PHP splits by every match unless you manipulate the pattern itself.

A cleaner regex approach uses a negative lookbehind or simply captures everything up to the final delimiter if you are certain about the position. But often, the logic required to make regex "look ahead" for the last specific instance is more complex than it appears and can hurt readability. For instance, you might try to match the string up to the second-to-last underscore, but that requires counting occurrences beforehand, which essentially replicates the logic of the slice method.

Trade-offs and Pitfalls

The primary trade-off here is performance versus clarity. The explode + array_slice approach adds a linear pass to join the characters back together. For massive strings with thousands of delimiters, this overhead is negligible compared to I/O costs. However, if you are processing millions of records in a tight loop, the extra memory allocation for the intermediate array created by explode before slicing might matter.

A common pitfall occurs when the string ends with the delimiter itself. In the example above, "one_two_ ... _three_four_", the final segment would be an empty string if you blindly apply the logic. You must ensure your application handles edge cases where the suffix is empty or missing. The explode function returns an array with an empty string for trailing delimiters; your reconstruction logic must account for whether that last element should actually exist in the result set or if it implies a malformed entry.

In modern Laravel applications, while you might find utility packages that abstract these string manipulations, understanding the underlying mechanics is crucial for debugging. If you encounter similar parsing needs within a Laravel project, checking out resources like LaravelCompany can provide further insights into handling complex string data structures within the framework's ecosystem.

Our network