Explode string by the last occurrence and get the first part

Coding Issue for android php java html-css and javascript

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 whole process will be done using Explode and Implode string in PHP. By using these techniques you can explode string by the last occurrence and get the first part.

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';

Also read this, because it’s helpful:

Arrange list items using drag and drop jQuery

If you want to split on any of the characters which are considered special by regular expressions, you’ll need to escape them first.

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if the string is empty.

Now, my requirement is:


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:

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case-sensitive regular expression pattern.


Published by Tirthraj Pandey

Professional Android app Developer, Full Stack Web Developer, Blogger, Entrepreneur And Founder of Coding Issue. I am always trying to learn new things or new possible ways to do things.

Did you find this page helpful?


Leave a Reply

Your email address will not be published. Required fields are marked *




One Reply to Post


June 17, 2019

Hi, this is a comment for your good article.
Good work.