Explode string by last occurrence and get first part

Explode string by last occurrence and get 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

 

Loading...

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 )

 

Loading...

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

Related posts

Write a comment