Xeen
Xeen

Reputation: 7003

How to remove last element from URL with PHP?

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

Answers (5)

Avinash Raj
Avinash Raj

Reputation: 174706

You may use preg_replace function.

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

DEMO

Upvotes: 1

menakas
menakas

Reputation: 376

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

returns
extra example.com/en/category/node

Upvotes: 2

Raghavendra
Raghavendra

Reputation: 3580

try this as your regex

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

Upvotes: 0

MaggsWeb
MaggsWeb

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

Shiji.J
Shiji.J

Reputation: 1631

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.

Upvotes: 1

Related Questions