Trim variablesa off of a variable

I have

$referer = basename($_SERVER['HTTP_REFERER'],'.php');
echo "Referrer: $referer";

which for me produces
Referrer: edit_rack.php?id=14

how do I get it to produce
Referrer: edit_rack

There’s multiple ways of doing it, but you can use parse_url(). Then just take the path from the result and remove the leading forward slash. That should give you what you want.

I was looking a rtrim() but parse_url() is better?

Well, rtrim() trims only the part you specify off. parse_url() actually parses the URL and then gives you an array which consists of each different parts that make up the URL. It would also separate the ?id=14 from edit_rack.php for you. Then you would just have to remove parts of that file off such as the .php extension and the leading forward slash.

So if you were to use parse_url(), all you would have to then just do is

$parse = parse_url('');
print $parse['path'];

Which then gives you


which then you would just have to remove the / and .php from that string using strtr.


As @spaceshiptrooper mentioned there are “multiple ways”…

I would use this method:

$referer = substr( basename( __file__), 0, -4);

Just thought of another method which uses the faster function strstr:

$referer = strstr( basename(__file__), '.', true);

Anymore suggestions?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.