如何使用PHP从URL中删除最后一个元素?

I have $url = "example.com/en/category/node/extra/"; and I need to remove extra from $url, how could I do that?

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.

Many ways,

  1. explode pop last, then implode.

  2. Use regex replace the last part

  3. 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.

You may use preg_replace function.

preg_replace('~/[^/]*/([^/]*)$~', '//\1', $str);

DEMO

try this as your regex

[^/]+/$ //to get last and replace it with empty

$url = "example.com/en/category/node/extra/"; echo basename($url); echo dirname($url);

returns
extra example.com/en/category/node