Reputation: 7003
I have $url = "example.com/en/category/node/extra/";
and I need to remove extra
from $url
, how could I do that?
Upvotes: 2
Views: 5066
Reputation: 174706
You may use preg_replace
function.
preg_replace('~/[^/]*/([^/]*)$~', '//\1', $str);
Upvotes: 1
Reputation: 376
$url = "example.com/en/category/node/extra/";
echo basename($url);
echo dirname($url);
returns
extra
example.com/en/category/node
Upvotes: 2
Reputation: 3580
try this as your regex
[^/]+/$ //to get last and replace it with empty
Upvotes: 0
Reputation: 3027
Explode the $_SERVER['SCRIPT_URL'] into an array, remove empty elements, and then remove the last array element. Then, implode it all back together with initial and trailing slashes.
$urlArray = explode('/',$_SERVER['SCRIPT_URL']);
$urlArray = array_filter($urlArray);
// remove last element
array_pop($urlArray);
$urlString = '/'.implode('/',$urlArray).'/';
Don't store array_pop()
as a variable, unless you need the last array element.
Upvotes: 3
Reputation: 1631
Many ways,
explode pop last, then implode.
Use regex replace the last part
I prefer: append ../ to make it like "example.com/en/category/node/extra/../" because this cost less computation, and its more efficient
If you are interested in one of it and do not know how to do that exactly, leave me a comment.
Upvotes: 1