I am currently working on an MVC project in php and I need to get the path of the URL that I am entering in the following way:
Possible Entries (Examples)
- .stackoverflow.com/questions/ask
- .stackoverflow.com/questions/1
- .stackoverflow.com/questions/
Desired results:
- ask
- 1
- questions
For the specific purposes I have, I only work with numbers, but later I will have to work with any type of path. To solve my problem quickly use this function.
$vID=substr(str_replace("/", "", $_SERVER['REQUEST_URI']), -1);
This way I remove the "/" and get the last character. The problem is that this is only good for detecting single digit numbers. I removed the "/" so I would know that when I got an "e" it was because I was entering the template/ route.
I finally need to be able to find a way to get the last word after the last "/" and failing that, if there is nothing, it will return the last word before it.
Thank you so much guys!
You could do the following:
/
usingexplode
array_filter
.array_pop
Example:
Demo
How about you try splitting the parts of the string like so:
And you use a conditional for the last element of the chain:
So, in cases where you have "stackoverflow.com/questions/", take not the last element of the explode (which is a ""), but the penultimate element, which is "questions". The end function takes the last element of the array.