user1048676
user1048676

Reputation: 10066

Remove characters from end of URL

Say I have a URL with something like this:
http://website.com/website/webpage/?message=newexpense

I have the following code to try and get the the URL before the question mark:

$post_url = $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];

In this example I would get the following URL:
http://website.com/website/webpage/

I'd like to remove the webpage portion of this so the URL is:
http://website.com/website/

How can I do this?

Upvotes: 0

Views: 252

Answers (4)

CMF
CMF

Reputation: 31

Use parse_url This way you have all components.

$url = 'http://website.com/website/webpage/?message=newexpense';
$pUrl = parse_url( $url);
echo $pUrl['scheme'] . '://' . $pUrl['host'] . $pUrl['path'];

Upvotes: 2

Matt Gibson
Matt Gibson

Reputation: 38238

I'd probably use dirname; it's specifically designed to strip the last stuff after a "/"...

$url = "http://website.com/website/webpage/?message=newexpense";
echo dirname(dirname($url))."/"; // "http://website.com/website/"

(As it says in the documentation, "dirname() operates naively on the input string, and is not aware of the actual filesystem...", so it's quite safe to use for this kind of purpose.)

Upvotes: 1

Indra Kumar S
Indra Kumar S

Reputation: 2934

Try it with explode

<?php
$actual_link = "http://website.com/website/webpage/?message=newexpense]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];
$split=explode('/',  $add_income_url);
echo $split[0]."//".$split[2]."/".$split[3]."/";

?>

Even better is...

<?php
$actual_link = "http://website.com/website/webpage/?message=newexpense]";
$split=explode('/',  $actual_link);
echo $split[0]."//".$split[2]."/".$split[3]."/";

?>

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116110

You can do a similar trick using explode. Then pop the parts you don't need and implode the url back together. If you are sure that the part after '?' never contains a '/', you can replace your code with this one. If you're not sure, you should first remove the part after '/' and then run this code to remove the last part of the path.

<?php
$url = 'http://website.com/website/webpage/?message=newexpense';

$parts = explode('/', $url);

// Remove the last part from the array
$lastpart = array_pop($parts);

// If the last part is empty, or the last part starts with a '?'
// this means there was a '/' at the end of the url, so we 
// need to pop another part.
if ($lastpart == '' or substr($lastpart, 0, 1) == '?')
  array_pop($parts);

$url = implode('/', $parts);

var_dump($url);

Upvotes: 1

Related Questions