Skip to content

PHP Explode Last Occurrence: Get the First Part

PHP Explode Last Occurrence: Get the First Part

Some of the cases we need to split any string or it may be my URL to split. Now I am explaining to you, how to explode the string by the last occurrence at getting the first part of the string in a single line. This who;e process will be done using Explode and Implode string in PHP.

In my case, I am trying to split my URL and get the URL before the last occurrence. My URL is:

$path = 'http://localhost/blog/public/home/page/15';

 

Now, my requirement is:

http://localhost/blog/public/home/page

 

So, now first we need to Explode the URL by "/".

explode('/', $path, -1);

I have used (-1) as a third parameter of explode(). because I want to ignore the last occurrence of the URL.

 

After exploding this URL by "/", my result should be like this:

Array ( [0] => http: [1] => [2] => localhost [3] => blog [4] => public [5] => home [6] => page )

 

Now I am going to implode this array URL by "/":

$URL = implode(explode('/', $path, -1), '/');

 

Finally, my result is:

http://localhost/blog/public/home/page

What Does Splitting at the Last Occurrence Mean?

Separate the final segment

Many PHP tasks need everything before the final delimiter. A URL may contain several slashes, a file path may contain several directories, or a dotted value may contain multiple periods. The important position is the last occurrence, not the first one.

For example, the path /blog/public/home/page/15 contains several slashes. If the final segment is an identifier, the desired result may be /blog/public/home/page. The solution should preserve the earlier separators instead of splitting the string into unrelated pieces permanently.

Choose the right interpretation

Before using a string function, decide whether the input is a URL, a filesystem path, a filename, or arbitrary text. Dedicated parsing functions are safer for structured data, while explode and implode are useful when the delimiter rule is simple and known.

Understand explode() and implode()

Turn a string into an array

explode() separates a string at every occurrence of a delimiter and returns an array of pieces. For a slash-delimited path, each directory or segment becomes an array element. The function does not know whether the input is a valid URL or path; it only follows the delimiter you provide.

$path = '/blog/public/home/page/15';
$parts = explode('/', $path);

Inspect the result while developing, especially when the input begins or ends with a delimiter. A leading slash creates an empty first element, which may be correct and should not be removed without a reason.

Join pieces with implode()

implode() joins array values using a separator and returns one string. The separator should normally be passed explicitly so the output format is obvious:

$withoutLast = array_slice($parts, 0, -1);
$result = implode('/', $withoutLast);

This two-step form is easy to debug. It lets you inspect the array before joining it and makes the removal of the final element visible to a reader.

Use explode() with a Negative Limit

PHP last delimiter workflow
PHP Last-Delimiter Workflow

How the negative limit works

PHP's explode() accepts an optional limit. A negative limit removes that many elements from the end of the returned array. With -1, the final piece is omitted from the result.

$path = 'http://localhost/blog/public/home/page/15';
$parts = explode('/', $path, -1);
$result = implode('/', $parts);
echo $result;

The result is http://localhost/blog/public/home/page. This is the compact version of splitting, removing the last array element, and joining the remaining values.

Understand the limit before using it

A negative limit removes elements from the end, but it does not mean “find the last delimiter” through a separate search. If the input is short, empty, or lacks the delimiter, the output may not be what the caller expects. Validate the result when the operation is part of a security-sensitive or routing decision.

Get Everything Before the Last Delimiter

Compact helper function

function beforeLast(string $value, string $delimiter): string
{
    if ($delimiter === '' || strpos($value, $delimiter) === false) {
        return $value;
    }

    return implode($delimiter, explode($delimiter, $value, -1));
}

$result = beforeLast('/blog/public/home/page/15', '/');

The guard prevents an empty delimiter from producing an invalid operation and makes the no-match behavior explicit. Returning the original value is one possible policy; another application may return an empty string or a nullable result.

Preserve the protocol correctly

Splitting a URL by slash also splits the protocol marker into pieces. Rejoining with the same slash preserves the visible URL in ordinary cases, but this is still a string operation rather than URL validation. If the input may contain query strings, fragments, encoded slashes, or unusual schemes, parse those components deliberately.

Handle Query Strings and Fragments

Separate the URL components first

A URL such as /article/15?mode=full#comments contains a path, query string, and fragment. Removing the last path segment from the complete string without considering those components can produce an incorrect result.

$url = '/article/15?mode=full#comments';
$parts = parse_url($url);
$path = $parts['path'] ?? '';
$basePath = implode('/', explode('/', $path, -1));

After changing the path, rebuild the query and fragment according to the application's needs. Do not assume that a slash inside a query value represents a path separator.

Encoded data is not ordinary text

Encoded separators, percent-encoded values, and internationalized URLs need careful treatment. Decode and re-encode only at the correct layer. Blindly changing the complete URL can alter data that was meant to remain inside a query parameter.

Deal with Missing and Repeated Delimiters

No matching delimiter

When the delimiter is absent, there is no final separator to remove. Decide whether the function should return the original string, an empty value, or a failure indicator. Document that choice so callers do not confuse a valid one-part value with an error.

Trailing and repeated slashes

Inputs such as /one/two/ and //one//two contain empty segments. These may be meaningful in a path or may indicate poor normalization. Do not call array_filter() automatically because it removes empty values and can change the structure.

$parts = explode('/', '/one/two/');
// The final element is empty because the input ends with '/'.

If normalization is required, define it as a separate step and test leading slashes, trailing slashes, and repeated separators.

Alternative Methods with strrpos() and substr()

Find the final position directly

strrpos() returns the position of the last occurrence of a substring. Once that position is known, substr() can return everything before it:

$path = '/blog/public/home/page/15';
$position = strrpos($path, '/');
$result = $position === false ? $path : substr($path, 0, $position);

This approach avoids creating an array when only the portion before the final delimiter is needed. It also makes the no-delimiter case explicit.

Choose based on readability

The negative-limit explode version is concise and familiar for simple delimiter work. The strrpos and substr version communicates the exact operation and can be easier to extend when the final position is also needed. Use the form that makes the edge-case behavior clearest to your team.

Use pathinfo() for File Paths

Do not parse every path manually

For a filesystem path, PHP's pathinfo() can expose the directory name, base name, filename, and extension. It is often a better fit than splitting on every slash when the task is about a file rather than a generic string.

$file = '/var/www/site/report.pdf';
$directory = pathinfo($file, PATHINFO_DIRNAME);
$filename = pathinfo($file, PATHINFO_BASENAME);

Use URL parsing for URLs and filesystem functions for filesystem paths. Similar-looking separators do not make the two data types interchangeable.

Validate and Normalize the Result

Check input types and limits

Type declarations can prevent accidental arrays or null values from reaching a string helper. Validate a delimiter before calling the function and set a clear policy for empty input. Do not silently cast unexpected data when the result controls a file or route.

Keep the result predictable

A helper should have a documented result for a missing delimiter, an empty delimiter, a trailing delimiter, and a one-segment string. Predictability is more valuable than a compact expression that hides several assumptions.

Common PHP String-Splitting Mistakes

Confusing an array with a string

explode() returns an array, while implode() returns a string. Echoing the array directly will not produce the intended path. Join the values after removing or selecting the required segments.

Removing the wrong element

array_shift() removes the first value, while array_pop() removes the last. Choose the operation that matches the requirement and remember that a leading slash may create an empty first element.

Ignoring user-controlled input

Never treat a path string as trusted simply because it was split successfully. Validate route segments, normalize allowed values, and use the appropriate filesystem or framework safeguards before opening files or building redirects.

Practical Comparison

MethodBest useImportant consideration
explode with negative limitSimple delimiter stringsReturns an array before joining
strrpos and substrEverything before one final delimiterHandle no-match positions
pathinfoFilesystem paths and extensionsUse for files, not arbitrary URLs
parse_urlURL componentsHandle path, query, and fragment separately

FAQ

How do I get everything before the last slash in PHP?

Use implode('/', explode('/', $value, -1)) for a simple delimiter string, or use strrpos() and substr() when you want direct position control.

What does a negative limit do in explode()?

It removes that number of elements from the end of the returned array. A limit of -1 omits the final element.

How do I remove the last segment from a URL?

Parse the URL first when it may contain a query or fragment, operate on the path, and then rebuild the components. For a simple path, a negative explode limit is sufficient.

Should I use explode() or strrpos()?

Use explode when the delimiter-based steps are easy to understand. Use strrpos and substr when only the final position matters or when you want explicit no-match handling.

How do I handle a missing delimiter?

Check for it and choose a documented result, such as returning the original string or a nullable failure value. Do not assume every input has the expected structure.

Conclusion

The PHP explode last occurrence technique is a practical way to remove the final segment from a simple delimiter-based string. Split with a negative limit and join the remaining values when the input is predictable.

For URLs, file paths, and user-controlled values, use the parser that matches the data type and handle empty, repeated, and missing delimiters explicitly. A few small checks make the helper safer and easier to maintain.

Write a comment