Explode string by the last occurrence and 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 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:
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 (  => http:  =>  => localhost  => blog  => public  => home  => 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.